[英]C/C++ expected primary-expression before “else”
can someone help me? 有人能帮我吗? im just starting programming on C/C++ (im using DevC++) 即时通讯刚刚开始在C / C ++上编程(即时通讯使用DevC ++)
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char* argv[]) {
int X;
int Y;
int R;
cout << "FUNCION POTENCIA";
cout << "Ingrese primero la base y luego el exponente";
cin >> X, Y;
if (Y = 1) {
R = X;
};
//if
else() {
do
while (Y > 0) {
R = X * X;
Y--;
}; //do while
}; //else cout<< R;
system("PAUSE");
return EXIT_SUCCESS;
} //main
You have five errors: 您有五个错误:
cin >> X, Y;
doesn't read user input to both X
and Y
. 不会同时读取X
和Y
用户输入。 It's actually two separate statements: cin >> X;
它实际上是两个单独的语句: cin >> X;
and Y;
和Y;
. 。 The first one reads user input to X
, the second one evaluates the current value of Y
and doesn't do anything to it. 第一个读取X
用户输入,第二个读取Y
的当前值,并且不对其执行任何操作。 To read user input to both variables: cin >> X >> Y;
要读取用户输入的两个变量: cin >> X >> Y;
. 。 if (Y = 1)
will assign 1
to Y
. if (Y = 1)
将1
分配给Y
You want to check for equality with ==
: if (Y == 1)
ie "if Y
is equal to 1
" . 您要使用==
检查是否相等 : if (Y == 1)
即“如果Y
等于1
” 。 if
, else
, and while
blocks. 不要在if
, else
和while
块之后放置分号。 They're redundant and cause errors like this. 它们是多余的,并且会导致此类错误。 Put semicolons only after statements . 仅在语句后放置分号。 ()
after else
. 不要把()
后, else
。 do { ... } while (...);
do-while循环是do { ... } while (...);
not do while (...) { ... }
, whereas a while loop is simply while (...) { ... }
. do while (...) { ... }
,而while循环只是while (...) { ... }
。 Here's the correct version: 这是正确的版本:
...
cin >> X >> Y; // 1.
if (Y == 1) { // 2.
R = X;
} // 3.
else { // 4.
while (Y > 0) { // 5.
R = X * X;
Y--;
}
// or if you want a do-while:
do {
R = X * X;
Y--;
} while (Y > 0); // semicolon here!
}
In conclusion, pick a book to learn the language properly, so you can stop guessing what the right syntax is. 总之,选择一本书以正确学习语言,这样您就可以停止猜测正确的语法是什么。
It's because you have a semicolon after your if statement. 这是因为if语句后有分号。 Correct if statement form is: 更正以下语句形式:
if(expression)
{
// If Code
}
else
{
// Else code
}
if (Y = 1) {
R = X;
};
Remove the last ";" 删除最后一个“;” here. 这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.