我的C++计算器似乎出了什么问题?

What seems to be wrong in my C++ calculator?

本文关键字:什么 问题 C++ 计算器 我的      更新时间:2023-10-16
#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