这个c ++代码有什么问题

时间:2015-07-03 02:30:54

标签: c++ debugging

我是初学者学习代码,我正在复制用于编程教学的YouTube视频。但是当我编写代码时,它会导致一些错误。

以下是代码:

#include <iostream>
using namespace std; 
int main()
{
    int num1 , num2;

    cout<< " Enter number 1 and number 2 \n";
    cin>> num1 >> num2;

    if (num1 == num2);
        cout<< "The both numbers are equal \n";

    else if (num1> num2)
        cout<< "Number 1 is greater than number 2 \n";
    else (num1< num2)
        cout<< "Number 2 is greater than number 1 \n";

    return 0;
}

3 个答案:

答案 0 :(得分:8)

请注意,;表示表达式结束,因此您应该更改

if (num1 == num2);

if (num1 == num2)

else不需要条件,因此请更改

else (num1< num2)

else

答案 1 :(得分:1)

  1. ;条件检查后您不需要if

  2. 如果您想进行条件检查,则应使用else if,在这种情况下else是不够的:

    #include <iostream>
    using namespace std; 
    int main()
    {
        int num1 , num2;
    
        cout<< " Enter number 1 and number 2 \n";
        cin>> num1 >> num2;
    
        if (num1 == num2)
            cout<< "The both numbers are equal \n";
        else if (num1> num2)
            cout<< "Number 1 is greater than number 2 \n";
        else if (num1< num2)
            cout<< "Number 2 is greater than number 1 \n";  
        return 0;
    }
    

答案 2 :(得分:1)

;   is not placed after `if` condition 

此外,否则没有得到条件......它总是检查对应的if的否定。  实际上,如果if的条件不能保存else块中的代码,则执行....通过更改

 else (num1< num2)
        cout<< "Number 2 is greater than number 1 \n";  

 else
        cout<< "Number 2 is greater than number 1 \n";

你的问题将得到解决。