在我的程序中使用if、else-if和else语句的c++?(新手)

c++ with the if, else if, and else statements on my program? (newbie)

本文关键字:语句 else c++ 新手 else-if 程序 我的 if      更新时间:2023-10-16

我不明白循环if语句,也不明白为什么我的程序不能正常工作。该程序将根据你的输入反映你的成绩。有人明白为什么它不起作用吗?

#include <iostream>
using namespace std;
int main()
{
    int grade;
    cout << "What grade did you earn in Programming I ?" << endl;
    cin >> grade;
    if (grade = 'A')
        cout << "an A - excellent work !" << endl;
    if (grade = 'B')
        cout << "you got a B - good job" << endl;
    else if (grade = 'C')
        cout << "earning a C is satisfactory" << endl;
    else if (grade = 'D')
        cout << "while D is passing, there is a problem" << endl;
    else if (grade = 'F')
        cout << "you failed - better luck next time" << endl;
    else
        cout << "You did not enter an A,B,C,D or F" << endl;
    return 0;
}

问题在if条件下的=中。

=是赋值运算符,而==是等式比较运算符。

当您为int指定一个值时,它也会计算为true,因此if条件也会得到满足。

此外,如注释中所述,将等级的数据类型从int更改为char