首页 > 代码库 > c++ primer 4.7节练习答案

c++ primer 4.7节练习答案

练习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         else
13             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节练习答案