【问题标题】:Error while using If else使用 If else 时出错
【发布时间】:2018-08-25 03:55:01
【问题描述】:

我正在尝试创建一个程序,您需要输入 3 个数字并需要告诉您哪个更大,我收到错误:[Error] expected '(' before 'else'. 错误在第 17 和 21 行。 这是代码。

using namespace std;


int main(){

  int n1, n2, n3;

  cout<<"Type 3 numbers : ";
  cin>>n1>>n2>>n3;

  if (n1 > n2 && n1 > n3){
    cout<<"The graeter is : "<<n1;
  } 
  if else{
    (n2 > n3);
    cout<<"The graeter is: "<<n2;
  }
  if else {
    cout<<"The graeter is: "<<n3;
  } 
  return 0;
}

【问题讨论】:

    标签: dev-c++


    【解决方案1】:

    您已将if else 放在应为else if 的位置。您还将条件放在代码块中。在您的最终测试中,您只有else,因为除此之外没有其他选择。试试这个:

    int main()
    { 
      int n1, n2, n3;
    
      cout<<"Type 3 numbers : ";
      cin>>n1>>n2>>n3;
    
      if (n1 > n2 && n1 > n3) {
        cout<<"The greater is : "<<n1;
      }
      else if (n2 > n3) {
        cout<<"The greater is: "<<n2;
      }
      else {
        cout<<"The greater is: "<<n3;
      }
      return 0;
    }
    

    我目前无法运行它,所以可能还有其他我没有发现的错误。

    一些程序员建议放入括号以确保您的意图是明确的(请参阅Dangling Else Problem),但在这种情况下没有必要。

    【讨论】:

    • 很高兴听到它有帮助。请接受答案并投票!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多