[英]Getting a “expected Primary Expression before else”
I have looked at about 15 pages and corrections of this problem but just can't crack it. 我看了大约15页并更正了这个问题,但无法破解。 If someone could advise I would be eternally grateful! 如果有人能告诉我,我将永远感激不已!
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int exres = 100;
if (exres = 100)
{
cout << "Perfect Score!";
else
cout << "try again";
}
system("PAUSE");
return EXIT_SUCCESS;
}
Your if
statement syntax is incorrect. 您的if
语句语法不正确。 Each part of the if
statement should be in its own block (within {
and }
s). if
语句的每个部分都应该在自己的块中(在{
和}
内)。
if (exres == 100)
{
cout << "Perfect Score!";
}
else
{
cout << "try again";
}
If the blocks each consist of a single statement (as they do in this case), then the braces can be omitted altogether: 如果每个块都由一个语句组成(如本例所示),则可以完全省略括号:
if (exres == 100)
cout << "Perfect Score!";
else
cout << "try again";
However, I recommend using braces at all times. 但是,我建议始终使用大括号。
Notice also that your assignment operator ( =
) should be the equality operator ( ==
) instead. 还要注意,您的赋值运算符( =
)应该改为相等运算符( ==
)。
You made two errors. 您犯了两个错误。 The else statement has no a corresponding if statement and instead of the comparison operator you used the assignment operator in statement else语句没有相应的if语句,您在语句中使用了赋值运算符,而不是比较运算符
if (exres = 100)
Also I would insert endl
in output statements 我也会在输出语句中插入endl
if ( exres == 100)
{
cout << "Perfect Score!" << endl;
}
else
{
cout << "try again" << endl;
}
Also nobody is able to repeat the attempt because you set yourself the value of exres. 同样,没有人能够重复尝试,因为您为自己设置了表达的价值。 I would write the program the following way 我将以以下方式编写程序
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
while ( true )
{
cout << "Enter your score: ";
unsigned int exres = 0;
cin >> exres;
if ( exres == 0 ) break;
if ( exres == 100)
{
cout << "Perfect Score!" << endl;
}
else
{
cout << "try again" << endl;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.