5.5
@Mooophy
#include <iostream>
#include <vector>
#include <string>
using std::vector; using std::string; using std::cout; using std::endl; using std::cin;
int main()
{
vector<string> scores = { "F", "D", "C", "B", "A", "A++" };
for (int g; cin >> g;)
{
string letter;
if (g < 60)
{
letter = scores[0];
}
else
{
letter = scores[(g - 50) / 10];
if (g != 100)
letter += g % 10 > 7 ? "+" : g % 10 < 3 ? "-" : "";
cout << letter << endl;
}
}
return 0;
}
5.6
#include <iostream>
#include <vector>
#include <string>
using std::vector; using std::string; using std::cout; using std::endl; using std::cin;
int main()
{
vector<string> scores = { "F", "D", "C", "B", "A", "A++" };
int grade = 0;
while (cin >> grade)
{
string lettergrade = grade < 60 ? scores[0] : scores[(grade - 50) / 10];
lettergrade += (grade == 100 || grade < 60) ? "" : (grade % 10 > 7) ? "+" : (grade % 10 < 3) ? "-" : "";
cout << lettergrade << endl;
}
return 0;
}
5.7
(a) if (ival1 != ival2) ival1 = ival2 //缺少一个分号
else ival1 = ival2 = 0;
(b) if (ival < minval) minval = ival;
occurs = 1; //缺少花括号括起来
(c) if (int ival = get_value())
cout << "ival = " << ival << endl;
if (!ival) //要使用else if ?
cout << "ival = 0\n";
(d) if (ival = 0) //使用 ==
ival = get_value();
5.8
经常会出现 if 比else多的情况
else 一般和离它最近的if 匹配成一对