You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ if else语句代码报错求助:main函数返回值错误与clrscr未定义问题

Hi there! Let's walk through fixing your C++ code step by step—you've got a few small standard compliance and syntax issues here, but they're easy to resolve.

1. Fix the main function return type

C++ standards require that the main function returns an int type, not void. Your compiler is throwing an error because void main() isn't valid standard C++. To fix this:

  • Change void main() to int main()
  • Add return 0; at the end of the function (this tells the OS the program ran successfully)

2. Remove non-standard <conio.h> and clrscr()/getch()

<conio.h> is a legacy DOS header that's not supported by most modern compilers (like GCC, Clang, or even recent MSVC versions). The functions clrscr() (clear screen) and getch() (wait for key press) are non-standard too:

  • Delete #include<conio.h> entirely
  • Remove the clrscr(); line (if you still want to clear the screen, you'd need a platform-specific method—for example, system("cls") on Windows or system("clear") on Linux/macOS, but note that system() isn't ideal for production code)
  • Replace getch(); with standard input methods to pause the program (we'll cover this in the corrected code)

3. Fix the equality comparison bug

In your else if condition, you used vari=vari2—this is an assignment operator, not a comparison. It sets vari to the value of vari2 and then evaluates to that value (which will always be true unless vari2 is 0). To check if the two variables are equal, use the equality operator ==:
Change else if (vari=vari2) to else if (vari == vari2)

Corrected Full Code

#include<iostream>
using namespace std;

int main()
{
    int vari, vari2;
    cout << "Enter a Variable: ";
    cin >> vari;
    cout << "Enter Another Variable: ";
    cin >> vari2;

    if (vari > vari2) {
        cout << "Variable 1 was greater";
    }
    else if (vari == vari2) {
        cout << "Variables Are Equal";
    }
    else {
        cout << "Variable 2 is Greater";
    }

    cin.get();
    cin.get(); // Two calls fix the leftover newline from previous cin inputs
    return 0;
}

(Note: The second cin.get() is needed because after entering the second number with cin, there's a leftover newline character in the input buffer—without it, the first cin.get() would just read that newline and exit immediately.)

内容的提问来源于stack exchange,提问作者Kushagra Pandey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:03:12