4.21
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> ivec{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (auto i : ivec) {
cout << ((i % 2) ? i : i * 2) << " ";
}
cout << endl;
return 0;
}
4.22
#include <iostream>
using namespace std;
int main()
{
for (unsigned g; cin >> g; )
{
auto result = g > 90 ? "high pass" : g < 60 ? "fail" : g < 75 ? "low pass" : "pass";
cout << result << endl;
if (g > 90) cout << "high pass";
else if (g < 60) cout << "fail";
else if (g < 75) cout << "low pass";
else cout << "pass";
cout << endl;
}
return 0;
}
if更容易理解 ,但是用条件运算符,代码会简洁很多,倾向于使用条件运算符
4.23
string s = "word";
string pl = s + s[s.size() - 1] == 's' ? "" : "s" ;
改正:
string pl = s + (s[s.size() - 1] == 's' ? "" : "s") ;
当你不确定优先级的时候,请使用括号来明确表达你的意图
4.24
boring