首页 > 代码库 > C++primer 9.5.5节练习
C++primer 9.5.5节练习
练习9.50
1 #include<iostream> 2 #include<string> 3 #include<vector> 4 5 using namespace std; 6 7 int main() 8 { 9 int sum = 0; 10 int num; 11 vector<string> vec{ "12","23","1","34","13","99" }; 12 for (auto it = vec.begin(); it != vec.end(); ++it) 13 { 14 num = stoi(*it); 15 sum += num; 16 } 17 cout << sum << endl; 18 system("pause"); 19 return 0; 20 }
修改后
1 #include<iostream> 2 #include<string> 3 #include<vector> 4 5 using namespace std; 6 7 int main() 8 { 9 double sum = 0; 10 double num; 11 vector<string> vec{ "12.0","23.9","1.0","34.0","13.0","99.0" }; 12 for (auto it = vec.begin(); it != vec.end(); ++it) 13 { 14 num = stod(*it); 15 sum += num; 16 } 17 cout << sum << endl; 18 system("pause"); 19 return 0; 20 }
练习9.51
比较麻烦,截取其中一个做做实验,关键是掌握各种函数的用法
1 #include<iostream> 2 #include<string> 3 #include<vector> 4 5 using namespace std; 6 7 class date { 8 friend ostream &print(ostream &os, date &d); 9 public: 10 date(unsigned y, unsigned m, unsigned d) : years(y), month(m),days(d){} 11 date() : date(1990,1,1) {} 12 date(string &s); 13 14 private: 15 unsigned years; 16 unsigned month; 17 unsigned days; 18 }; 19 20 ostream &print(ostream &os, date &d); 21 22 int main() 23 { 24 string s{ "1/1/1990" }; 25 date d1(s); 26 print(cout, d1); 27 system("pause"); 28 return 0; 29 } 30 31 date::date(string &s) 32 { 33 days = stoi(s.substr(0, s.find_first_of(‘/‘) - 0)); 34 month = stoi(s.substr(s.find_first_of(‘/‘) + 1, s.find_last_of(‘/‘) - s.find_first_of(‘/‘) -1)); 35 years = stoi(s.substr(s.find_last_of(‘/‘) + 1)); 36 } 37 38 ostream & print(ostream & os, date & d) 39 { 40 os << d.years << " " << d.month << " " << d.days; 41 return os; 42 // TODO: 在此处插入 return 语句 43 }
C++primer 9.5.5节练习
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。