c++ - Integer 在 VSCommunity2019,windows10 中未初始化
问题描述
我正在用 c++ 制作一个计算器,除了有一个问题的阶乘之外,我已经完成了所有工作:我的 int 编号是“未初始化”,如果有帮助,这是 windows10 上 vscommunity2019 上的控制台应用程序。除了阶乘之外,一切都很完美,当我测试它时,唯一的错误是 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(在编译资源管理器中尝试时,它会编译,但我认为会有运行时错误)。
解决方案?可能在循环中替换为,并number
输出.n1
fact
推荐阅读
- java - 如何在 REST API 中使用下划线将驼峰大小写转换为小写?
- html - 内容响应式 HTML 表格
- javascript - 有没有办法更改本地存储中的键名。例如:
- python - 为什么 cross_val_score 与我手动计算时不同?
- google-chrome - 桌面谷歌浏览器拼写检查是否受操作系统影响?
- httpwebresponse - How to fix Veracode error "Server-Side Request Forgery (SSRF)" when using HttpWebResponse?
- android - React-Native Error: Unable to resolve module
- computer-vision - 立体系统中的三角测量导致的深度误差
- html - 至少 3 个单词或更多,但使用阿拉伯语 [HTML 模式]
- python - 在多字串的空格之间添加一个字符