这在C++中不正确吗?

Isn't this correct in C++?

本文关键字:不正确 C++ 这在      更新时间:2023-10-16
    #include <iostream>
using namespace std;
int main()
{
    int szam,tart;
    cout << "Num=";
    cin >> szam;
    while(szam!=tart){
        tart=szam;
        cout << "Now insert a number which is not " << tart << "n Your number is=";
        cin >> szam;
        if(szam==tart)
            cout << "And you failed.";
    }
    return 0;
}

此代码不正确吗?我的老师一直说这是不正确的,因为我应该称呼" t"变量的值,例如" cin>> tart"。

请尽快回答。

由于 tart在使用之前尚未分配给(在比较中),因此初始比较的结果是不确定的行为。

它是不形式的海湾合作委员会,甚至会给您一个诊断:

main.cpp:13:15: warning: 'tart' may be used uninitialized in this function [-Wmaybe-uninitialized]
     while(szam!=tart){
           ~~~~^~~~~~

使用非专业化变量是未定义的行为。

这是正确的,但是您应该给蛋t的值一个值。否则,它将使用随机的一个。

" int tart;"确实创建了一个名为int类型的变量,但是未设置其值(未定义),这意味着如果使用它,它可以并且(大多数时间)将导致错误。

#include <iostream>
using namespace std;
int main()
{
    int szam;
    int tart=0;//need to initialize or need to call  cin >> tart;
    cout << "Num=";
    cin >> szam;
    while(szam!=tart){
        tart=szam;
        cout << "Now insert a number which is not " << tart << "n Your number is=";
        cin >> szam;
        if(szam==tart)
            cout << "And you failed.";
    }
    return 0;
}