分數分級
問題:
將分數依 A:100~90 B:80~89 C:70~79 D:60~69 E:0~59 分等級
做法有以下幾種:
- 用if
- 用switch+除以10
- 用除以10+陣列解(最漂亮,一行的程式就解決問題!)
1.
//score為分數變數,浮點數,grade為等級變數,字元
if (score <= 100 && score >= 90) grade = 'A';
if (score <= 89 && score >= 80) grade = 'B';
if (score <= 79 && score >= 70) grade = 'C';
if (score <= 69 && score >= 60) grade = 'D';
if (score <= 59) grade = 'E';
2.除以10去掉個位數,判斷上就會較簡單
float score; char grade;
cout << "請輸入成績:"; cin >> score;
score = (int)(score / 10); //去掉個位數
if (score == 10 ||
score == 9)
grade = 'A';
else if (score == 8) grade = 'B';
else if (score == 7) grade = 'C';
else if (score == 6) grade = 'D';
else grade = 'E';
cout << "你的成績等級是:" << grade << endl;
3.除以10去掉個位數,用switch
float score; char grade;
cout << "請輸入成績:"; cin >> score;
int s = (int)(score / 10); //去掉個位數
switch (s) {
case 10:
case 9: grade = 'A'; break;
case 8: grade = 'B'; break;
case 7: grade = 'C'; break;
case 6: grade = 'D'; break;
default: grade = 'E';
}
cout << "你的成績等級是:" << grade << endl;