標籤:double using ios pause turn names c++ signed date()
練習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節練習