整数在VSCommunity2019,windows10中未初始化

Integer is uninitialized in VSCommunity2019,windows10

本文关键字:初始化 windows10 VSCommunity2019 整数      更新时间:2023-10-16

我正在用 c++ 制作一个计算器,除了阶乘之外,我完成了所有工作,它有一个问题: 我的 int 编号是"未初始化"的,这是 Windows2019 上的 VSHaCommunity10 上的控制台应用程序,如果有帮助的话。除了阶乘之外,一切都很完美,当我测试它时,唯一的错误是 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;

}

好吧,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;
[...]
}

幸运的是,您会收到编译错误并且可以修复它(感谢MSVC!对于 gcc(在编译资源管理器中尝试时,它会编译,但我认为会出现运行时错误(。

溶液?可能会将循环中的n1替换number,并输出fact.