简体   繁体   English

使用 else if 时预期语句错误

[英]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.我试图查看 output 但它总是返回“预期的语句”错误消息。 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 .在 C 和 C++ 中, if适用于下一条语句 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 <<... . if适用于p =... ,这是下一条语句,它不适用于之后的语句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.两个花括号标记一个复合语句,它是一个语句, if适用于整个语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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