简体   繁体   中英

Expected a statement error while using else if

I'm trying to see the output but it always returns the "expected a statement" error message. I would appreciate any help, thanks.

#include <iostream>

#include "stdafx.h"

using namespace std;

int main() {
  int const n = 6;

  int A[n] = {1, -2, 3, -4, 5, -6}, i, p, x;
  int T[n] = {1, 3, 5};
  int U[n] = {-2, -4, -6};

  p = 1;
  x = 1;

  for (i = 0; i < n; i++) {
    if (A[i] < 0) p = p * U[i] * U[i];
    cout << "Test" << p << "\n";

    else if (A[i] > 0) {
      x = x * T[i] * T[i] * T[i];

      cout << "Test2" << X << "\n";
    }
  }
  return 0
}

It's simple, you are missing {}

if (A[i] < 0)
{                          // <--- here
    p = p * U[i] * U[i];
    cout << "Test" << p << "\n";
}                          // <--- and here
else if (A[i] > 0)
{ 
    x = x * T[i] * T[i] * T[i];
    cout << "Test2" << X << "\n";
}

In C and C++, if applies to the next statement . So when you write

if (A[i] < 0)
p = p * U[i] * U[i];
cout << "Test" << p << "\n";

the if applies to p =... , which is the next statement, and it does not apply to the statement after that, cout <<... .

To turn two statements into one, use a compound statement :

if (A[i] < 0)
{
p = p * U[i] * U[i];
cout << "Test" << p << "\n";
}

The two curly braces mark a compound statement, which is one statement, and the if applies to that entire statement.

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