C++primer 9.5.5節練習

來源:互聯網
上載者:User

標籤: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節練習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.