首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

杭電 OJ 2004:分數等級轉換 - C 語言條件判斷練習

     編輯:關於C語言

題目描述

輸入一個整數分數(0-100),輸出對應等級:

  • 90-100:A
  • 80-89:B
  • 70-79:C
  • 60-69:D
  • 0-59:E
  • 其他:Score is error!

多組測試數據,EOF 結束。

參考代碼

#include <stdio.h>

int main(void) {
    int score;

    while (scanf("%d", &score) != EOF) {
        if (score >= 0 && score < 60)
            printf("E\n");
        else if (score >= 60 && score < 70)
            printf("D\n");
        else if (score >= 70 && score < 80)
            printf("C\n");
        else if (score >= 80 && score < 90)
            printf("B\n");
        else if (score >= 90 && score <= 100)
            printf("A\n");
        else
            printf("Score is error!\n");
    }

    return 0;
}

代碼優化說明

原始代碼存在多餘的 `else` 和格式混亂問題。優化後:

  • 使用 `else if` 鏈,條件互斥,避免重複判斷
  • 條件順序從低到高(或高到低)均可,邏輯清晰
  • 去除原代碼中的 `elsewww.2cto.com` 等雜質字符

邊界測試

輸入輸出說明
95A正常範圍
90A邊界值
89B邊界值
60D及格線
59E不及格
-1Score is error!非法輸入
101Score is error!超出範圍

替代實現:Switch-Case

因 switch 不支援區間判斷,可結合除法技巧:

switch (score / 10) {
    case 10: case 9: printf("A\n"); break;
    case 8: printf("B\n"); break;
    case 7: printf("C\n"); break;
    case 6: printf("D\n"); break;
    default:
        if (score >= 0) printf("E\n");
        else printf("Score is error!\n");
}

但 if-else 版本可讀性更好,推薦使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved