题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2004
题目大意: 给你成绩让你根据成绩打分
解题思路:
简单的if...else 应用
需要注意是,if....else if ....else ..if....不能写成 if...if.....if....else .....
比如
1 int q; 2 int a = 12; 3 if(a == 10) 4 q = 1; 5 if(a == 12) 6 q = 2; 7 if(a == 1) 8 q = 3; 9 else 10 q = 4;
最后会进入到
1 if(a == 1) 2 q = 3; 3 else 4 q = 4;
所以最后输出要么 q 是 3,要么 q 是 4,就算 q 已经赋值为 2 了,还会进入到这个地方,重新判断,赋值,因为 if 之间没影响,到了 if...else...才算完整的一个排斥选择。
代码:
1 while(cin >> a) 2 { 3 if(a >= 90 && a <= 100) 4 q = 0; 5 else if(a >= 80 && a <= 89) 6 q = 1; 7 else if(a >= 70 && a <= 79) 8 q = 2; 9 else if(a >= 60 && a <= 69) 10 q = 3; 11 else if(a >= 0 && a <= 59) 12 q = 4; 13 else 14 q = -1; 15 if(q == -1) 16 cout << "Score is error!" << endl; 17 else 18 { 19 char m = q + 'A'; 20 cout << m << endl; 21 } 22 }
或者
1 while(cin >> score) 2 { 3 level = score / 10; 4 if(score > 100 || score < 0) 5 cout<<"Score is error!"<<endl; 6 else 7 { 8 switch(level) 9 { 10 case 10: 11 case 9: 12 cout << "A" << endl; 13 break; 14 case 8: 15 cout << "B" << endl; 16 break; 17 case 7: 18 cout << "C" << endl; 19 break; 20 case 6: 21 cout << "D" << endl; 22 break; 23 case 5: 24 case 4: 25 case 3: 26 case 2: 27 case 1: 28 case 0: 29 cout << "E" << endl; 30 break; 31 } 32 } 33 }