Visual Studio生成“错误:未初始化的局部变量'x'”,而在线编译器不生成-为什么?

1 c++ compiler-errors

int main() {
    int y, z, a, b, c;
    int x;
    double d;
    cout << "Enter Numbers! Enter -999 to Stop:\n";
    y = 0; z = 0; a = 0;
    b = 0; c = 0; d = 0;

while (x != -999) {

    cin >> x;

    if (x > 0) y++;
    if (x > 0) b += x;
    if (x == 0) z++;
    if (x < 0 && x != -999)a++;
    if (x < 0 && x != -999) c += x;



}
d = b * 1.0 / y * 1.0;
if (b == 0 || y == 0) {
    d = 0;
}

cout << "Total Positive Numbers are: " << y << endl;
cout << "Total Negative Numbers are: " << a << endl;
cout << "Total Zeros are: " << z << endl;
cout << "Sum of Positive Numbers is: " << b << endl;
cout << "Sum of Negative Numbers is: " << c << endl;
cout << "Average of Positive Numbers is: " << d * 1.0 << endl;
return 0;
Run Code Online (Sandbox Code Playgroud)

}

Visual Studio编译器在第13行说其“使用了未初始化的局部变量'x'”。

但是,在其他在线编译器上没有问题。

Bat*_*eba 8

Visual Studio在这里对您很友善:读取未初始化变量的行为在C ++中是未定义的,并且(x != -999)在第一次遇到时是未初始化的读取。

不要忽略其他编译器发出的警告。

  • @MemeReview:快速解决方法是在声明点将x设置为零。在您的编程生活的后期,您将采用更多的奇特方式。 (2认同)