我不理解循环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;
}
答案 0 :(得分:1)
问题出在=
if
条件中。
=
是赋值运算符,而==
是相等比较运算符。
当您为int
指定一个值时,它也会计算为true,因此if条件也会得到满足。
此外,正如评论中所述,将数据类型从int
更改为char
以获得成绩。