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

时间:2015-11-05 07:08:06

标签: c++ if-statement

我不理解循环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;
}

1 个答案:

答案 0 :(得分:1)

问题出在= if条件中。

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

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

此外,正如评论中所述,将数据类型从int更改为char以获得成绩。