简体   繁体   中英

C/C++ expected primary-expression before “else”

can someone help me? im just starting programming on C/C++ (im using 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:

  1. cin >> X, Y; doesn't read user input to both X and Y . It's actually two separate statements: cin >> X; and 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. To read user input to both variables: cin >> X >> Y; .
  2. if (Y = 1) will assign 1 to Y . You want to check for equality with == : if (Y == 1) ie "if Y is equal to 1 " .
  3. Don't put semicolons after if , else , and while blocks. They're redundant and cause errors like this. Put semicolons only after statements .
  4. Don't put () after else .
  5. A do-while loop is do { ... } while (...); not do while (...) { ... } , whereas a while loop is simply 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. Correct if statement form is:

if(expression)
{
     // If Code
}
else
{
     // Else code
}
 if (Y = 1) {
        R = X;
 };

Remove the last ";" here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM