我的C++计算器似乎出了什么问题?
What seems to be wrong in my C++ calculator?
#include <iostream>
using namespace std;
int main()
{
int num1,num2,answer;
char choice = 'Y',input;
while (choice == 'Y' || choice == 'y')
{
cout << "Enter the first number: " << endl;
cin >> num1;
cout << "Enter the second number: " << endl;
cin >> num2;
cout << "What operation would you like to use?" << endl << endl;
cout << "Press [A] if you want to use Addition." << endl;
cout << "Press [S] if you want to use Subtraction." << endl;
cout << "Press [M] if you want to use Multiplication." << endl;
cout << "Press [D] if you want to use Division." << endl;
switch(input)
{
case 'A':
case 'a':
{
answer=num1+num2;
cout << "This is the sum of your equation: " << answer << endl;
break;
}
case 'S':
case 's':
{
answer=num1-num2;
cout << "This is the difference of your equation: " << answer << endl;
break;
}
case 'M':
case 'm':
{
answer=num1*num2;
cout << "This is the product of your equation: " << answer << endl;
break;
}
case 'D':
case 'd':
{
answer=num1/num2;
cout << "This is the quotient of your equation: " << answer << endl;
break;
}
default:
{
cout << "Invalid Operation..." << endl;
break;
}
}
cout << "Do you want to go again? (Y/N) " << endl;
cin >> choice;
}
cout << "See you later." << endl;
return 0;
}
所以我大约一个半月前刚开始上大学,我想我应该尝试一下那些还没有教给我们的代码。但是我遇到了一个问题,每当我构建程序时,它都不会显示错误。但它并没有做我想要它做的事情,成为一个计算器。它立即跳到,"你想再去一次吗?输入 2 个数字后,它甚至不会让用户选择操作,更不用说计算它了。我的代码似乎有什么问题?
[编辑] 我忘了输入 cin>>;在询问使用哪个操作之后。
正如注释所建议的那样,您需要在某个时候为input
变量获取一个值。我会在依赖于它的switch
之前立即建议:
cin >> input; // You forgot to put this line in, I think!
switch(input)
{
...
如果提高编译器的警告级别,例如对 GCC 使用-Wall
,则会收到一个有用的警告,解释您的问题:
<source>: In function 'int main()':
<source>:8:19: warning: 'input' may be used uninitialized in this function [-Wmaybe-uninitialized]
8 | char choice = 'Y',input;
| ^~~~~
Compiler returned: 0
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了