简体   繁体   English

Integer在VSCommunity2019,windows10中未初始化

[英]Integer is uninitialized in VSCommunity2019,windows10

I am making a calculator in c++ and I have everyting done except factorial which has one issue: my int number is "uninitialized" this is a console application on vscommunity2019 on windows10 if that helps.我正在 c++ 中制作一个计算器,除了有一个问题的阶乘之外,我已经完成了所有工作:我的 int 编号是“未初始化”,这是 windows10 上 vscommunity2019 上的控制台应用程序,如果有帮助的话。 Everything works perfect except factorial,when I test it theonly error is the int number.除了阶乘之外,一切都很完美,当我测试它时,唯一的错误是 int 数。

#include <iostream>
using namespace std;
int main()

{
float n1;
char op;
float n2;
int co;
int i;
int fact = 1;
int number;
calculations: std::cout << "Enter n1!";
    std::cin >> n1;
    std::cout << "\nEnter operator! Here are your choices: + - * / !";
    std::cin >> op;
    std::cout << "\nEnter n2!";
    std::cin >> n2;
    switch (op)
    {
    case '+':
        std::cout << n1 + n2;
        break;
case '-':
    std::cout << n1 - n2;
    break;

case '*':
    std::cout << n1 * n2;
    break;

case '/':
    std::cout << n1 / n2;
    break;
case '!':
    for (i = 1; i <= number; i++) {
        fact = fact * i;
    }
    std::cout << number;
    break;
default:
    std::cout << "Error! operator is not correct";
    break;
}
std::cout << "\nWant to continue?Y(type 1)/N(type 0)";
std::cin >> co;
if (co == 1) {

    goto calculations;
}
return 0;


}

Well, number is uninitialized.好吧, number初始化。

int main()
{
int number; //uninitialized local variable
[...] //no usage of number
case '!':
    for (i = 1; i <= number; i++) { //first usage of number, before initializing it!
        fact = fact * i;
    }
    std::cout << number;
    break;
[...]
}

Luckily you get a compilation error and can fix it (thanks MSVC.), For gcc (when trying in compile explorer, it compiles. but I assume there will be a runtime error).幸运的是,你得到一个编译错误并且可以修复它(感谢 MSVC。),对于 gcc(在编译资源管理器中尝试时,它会编译。但我认为会有一个运行时错误)。

Solution?解决方案? Probably replace number with n1 in the loop, and output fact .可能在循环中用n1替换number ,以及 output fact

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM