You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++等级查询程序输入正确A-E字母后无法终止问题咨询

C++等级查询程序循环不终止问题解决方案

问题根因

你代码的核心错误来自以下3点:

  • 对C++逗号运算符的理解错误:逗号运算符不会用来判断变量是否属于某几个取值的范围,整个逗号表达式的最终值等于最后一个子表达式的返回值,你写的while(letter==A, B, C, D, E)等价于仅判断未初始化的变量E的值,而未初始化的局部char变量值是随机的,基本永远为真,导致循环不会终止。
  • 循环逻辑搞反:do-while循环的规则是条件为真时继续循环,你的需求是输入有效等级就退出循环、输入无效就继续请求输入,所以循环条件应该判断输入是否为无效值,而非有效值。
  • 冗余无效代码:你声明的char grades;、char A,B,C,D,E;以及赋值语句letter = A, B, C, D, E;没有任何实际作用,属于无效代码,直接删除即可。

修正后代码

#include <iostream>
#include <string>
using namespace std;
int main()
{
    char letter;
    do{
        cout << "\n Input grade letter: ";
        cin >> letter;
        if (letter=='A' || letter=='a')
        {
            cout << "Your grade is in the range of 96-100";
        }else if (letter=='B' || letter=='b')
        {
            cout << "Your grade is in the range of 91-95";
        }
        else if (letter=='C' || letter=='c')
        {
            cout << "Your grade is in the range of 86-90";
        }
        else if (letter=='D'|| letter=='d')
        {
            cout << "Your grade is in the range of 80-85";
        }
        else if (letter=='E'|| letter=='e')
        {
            cout << "Your grade is in the range of 79 and below";
        }
        else {
            cout << "Invalid Input! Try again!";
        }
    // 只有输入无效时才继续循环
    }while(!(letter=='A'||letter=='a'||letter=='B'||letter=='b'||letter=='C'||letter=='c'||letter=='D'||letter=='d'||letter=='E'||letter=='e'));
    cout<< "\nBye";
    return 0;
}

可选优化方案

如果觉得循环条件写的太长,可以先把输入是否有效的判断结果存在布尔变量里,同时用字符转小写函数减少重复判断,代码可读性更高:

#include <iostream>
#include <cctype> // 引入tolower函数统一转小写处理
using namespace std;
int main()
{
    char letter;
    bool is_valid;
    do{
        cout << "\n Input grade letter: ";
        cin >> letter;
        char lower_letter = tolower(letter);
        is_valid = true;
        switch(lower_letter) {
            case 'a': cout << "Your grade is in the range of 96-100"; break;
            case 'b': cout << "Your grade is in the range of 91-95"; break;
            case 'c': cout << "Your grade is in the range of 86-90"; break;
            case 'd': cout << "Your grade is in the range of 80-85"; break;
            case 'e': cout << "Your grade is in the range of 79 and below"; break;
            default: 
                cout << "Invalid Input! Try again!";
                is_valid = false;
        }
    }while(!is_valid);
    cout<< "\nBye";
    return 0;
}

内容的提问来源于stack exchange,提问作者maru11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:45:00