4.6


1 #include <iostream> 2 using namespace std; 3 int main() 4 { 5 cout << "Enter one number: " << endl; 6 int checkNum; 7 while (cin>>checkNum){ 8 if (checkNum % 2 == 1||checkNum%2==-1) 9 cout << "奇数" << endl; 10 else if (checkNum % 2 == 0) 11 cout << "偶数" << endl; 12 else 13 cout << "0既不是奇数也不是偶数" << endl; 14 } 15 system("pause"); 16 return 0; 17 }
4.10


1 #include <iostream> 2 #include <vector> 3 #include <string> 4 using namespace std; 5 int main() 6 { 7 int checkNum = 42,i; 8 while (cin >> i) { 9 if (i == checkNum){ 10 cout << "Get it!"; 11 break; 12 } 13 } 14 cout << endl; 15 system("pause"); 16 return 0; 17 }
4.11


1 #include <iostream> 2 #include <vector> 3 #include <string> 4 using namespace std; 5 int main() 6 { 7 int a, b, c, d; 8 cin >> a >> b >> c >> d; 9 if (a > b&&b > c&&c > d) { 10 cout << "yes,d<c<b<a"; 11 } 12 else 13 cout << "no"; 14 cout << endl; 15 system("pause"); 16 return 0; 17 }
P132 使用后置递增运算符输出直到遇到第一个负数


1 #include <iostream> 2 #include <vector> 3 #include <string> 4 using namespace std; 5 int main() 6 { 7 vector<int> vec{ 1,2,3,4,5,6,-1,2 }; 8 auto pbeg = vec.begin(); 9 while (pbeg != vec.end() && *pbeg >= 0) { 10 cout << *pbeg++ << endl; 11 } 12 system("pause"); 13 return 0; 14 }
4.17
前置运算符将对象本身作为左值返回,后置运算符则将对象原始值的副本作为右值返回。
P134


1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 int main() 5 { 6 int grade = 59; 7 string finalgrade = (grade < 60) ? "fail" : "pass"; 8 for (auto &c : finalgrade) 9 cout << c << ""; 10 cout << endl; 11 system("pause"); 12 return 0; 13 }
P134


1 #include <iostream> 2 #include <string> 3 using namespace std; 4 int main() 5 { 6 int grade; 7 while (cin >> grade) { 8 if (grade<=100&grade>0){ 9 string finalgrade = (grade >= 90) ? "high pass" : (grade < 60) ? "fail" : "pass"; 10 for (auto &c : finalgrade) { 11 cout << c << ""; 12 } 13 cout << endl; 14 } 15 } 16 system("pause"); 17 return 0; 18 }
4.21


1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 int main() 5 { 6 vector<int> nums{ 1,2,3,4,5,6,7,8,9 }; 7 for (auto &c : nums) { 8 int i = (c % 2 == 1) ? (c *= 2) : c; 9 cout << c << " "; 10 } 11 cout << endl; 12 system("pause"); 13 return 0; 14 }
4.22
条件运算符:


1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 int main() 5 { 6 int grade; 7 while (cin >> grade) { 8 string finalgrade = (grade > 90) ? "high pass" : (grade < 60) ? "fail" : (grade < 75) ? "low pass" : "pass"; 9 for (auto &c : finalgrade) { 10 cout << c << ""; 11 } 12 cout << endl; 13 } 14 system("pause"); 15 return 0; 16 }
if语句:


1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 int main() 5 { 6 int grade; 7 while (cin >> grade) { 8 if (grade > 90) { 9 cout << "high pass" << endl; 10 } 11 else if (grade >= 60) { 12 if (grade < 75) { 13 cout << "low pass" << endl; 14 } 15 else 16 cout << "pass" << endl; 17 } 18 else 19 cout << "fail" << endl; 20 } 21 system("pause"); 22 return 0; 23 }
4.25
移位运算符的优先级高于关系运算符、位运算符、赋值运算符和条件运算符。但是低于运算符。