【问题标题】:what is wrong in this easy if else c++ code? [closed]这个简单的 if else c++ 代码有什么问题? [关闭]
【发布时间】:2021-10-22 16:47:47
【问题描述】:

这个问题在hackerrank条件语句中,我想在不使用数组的情况下解决它。代码运行但输出错误。谁能看到这段代码有什么错误,为什么它不起作用?

#include <bits/stdc++.h>

using namespace std;


int n ;
cin >> n ;

int main()
{
    int n ;
    cin>>n;
    
    if(n=0){
        cout<<"zero";
    }
    else if(n=1){
        cout<<"one";
    }
    else if(n=2){
        cout<<"two";
    }
    else if(n=3){
        cout<<"three";
    }
    else if(n=4){
        cout<<"four";
    }
    else if(n=5){
        cout<<"five";
    }
    else if(n=6){
        cout<<"six";
    }
    else if(n=7){
        cout<<"seven";
    }
    else if(n=8){
        cout<<"eight";
    }
    else if(n=9){
        cout<<"nine";
    }
    else{
        cout<<"Greater than 9";
    }
    

    return 0;
}

【问题讨论】:

  • = 是一个赋值 == 是一个比较。不知道为什么你有这条线:int n ; cin &gt;&gt; n ;int main() 之前
  • #include &lt;bits/stdc++.h&gt; 与 Visual Studio 社区/企业/专业版(您标记了问题)不兼容。它可能适用于 VSCode 和 gcc,但这是另一回事。也是一种不好的做法:https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h
  • 还可以考虑使用switch 或数组。

标签: c++ if-statement visual-c++ conditional-statements rank


【解决方案1】:

您应该使用 '==' 而不是 '=' 因为“if (n=1)”的行为与“if(true)”的行为相同

== 是比较 = 是赋值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多