c++ primer 4.7節練習答案

來源:互聯網
上載者:User

標籤:過程   運算式   log   條件運算   out   運算子   大於   bsp   可讀性   

練習4.21

 1 int main() 2 { 3     int num; 4     vector<int> a_num; 5     while (cin >> num) 6         a_num.push_back(num); 7     for (auto &c : a_num) 8     { 9         (c % 2 != 0) ? (c = c * 2) : (c = c);10     }11     for (auto it = a_num.begin(); it != a_num.end(); ++it)12         cout << *it << endl;13     system("pause");14     return 0;15 }

練習4.22

版本1

 1 int main() 2 { 3     vector<int> grades{ 2,12,22,32,42,52,62,72,82,92 }; 4     for (auto c : grades) 5     { 6         string str = (c > 90) ? "high pass" : (c > 60) ? ((c < 75) ? "low pass" : "pass") : "fail"; 7         cout << str << endl; 8     } 9     system("pause");10     return 0;11 }

版本2

 1 int main() 2 { 3     vector<int> grades{ 2,12,22,32,42,52,62,72,82,92 }; 4     for (auto c : grades) 5     { 6         if (c < 60) 7             cout << "fail" << endl; 8         else if (c < 75) 9             cout << "low pass" << endl;10         else if (c < 90)11             cout << "pass" << endl;12         else13             cout << "high" << endl;14     }15     system("pause");16     return 0;17 }

可以很清楚的看到,版本2比版本1更加容易理解,在程式的易讀性上更加好,隨著條件運算嵌套層數的增加,代碼的可讀性急劇的下降,因此,條件運算的嵌套最好別超過兩到三層。

練習4.23

+運算子的優先順序大於==和?:

故這句話被理解為

string p1 = (s + s[s.size() - 1] == ‘s‘) ? "" : "s";此時因為string類型不可與char類型進行比較從而編譯不了;

可更改為

1 string p1 = s + (s[s.size() - 1] == ‘s‘ ? "" : "s");

練習4.24

求值的過程應該跟下面的運算式相同

1     finalgrade = (grade < 60) ? "file" : (grade > 90) ? "high pass" : "pass";

 

c++ primer 4.7節練習答案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.