C++ c++;多运算符计算器
所以我正在尝试制作一个可以使用多个运算符的计算器。我已经制作了一些可以使用2个数字(使用开关)的计算器程序,但是当我尝试使用2个以上的数字时,我真的无法让它工作。我有一个想法,但我不能实现它(我是编程新手); 下面是代码:C++ c++;多运算符计算器,c++,calculator,operator-keyword,C++,Calculator,Operator Keyword,所以我正在尝试制作一个可以使用多个运算符的计算器。我已经制作了一些可以使用2个数字(使用开关)的计算器程序,但是当我尝试使用2个以上的数字时,我真的无法让它工作。我有一个想法,但我不能实现它(我是编程新手); 下面是代码: // Simple arithmetic calculator. #include <iostream> using namespace std; int main() { float a, b, c, result; char op[2];
// Simple arithmetic calculator.
#include <iostream>
using namespace std;
int main()
{
float a, b, c, result;
char op[2];
// Get numbers and mathematical operator from user input
cin >> a >> op[0] >> b >> op[1] >> c;
result = a op[0] b op[1] c; // result = a + b - c if op[0]=+ and op[1]=-
// Output result
cout << result << endl;
return 0;
}
//简单算术计算器。
#包括
使用名称空间std;
int main()
{
浮动a、b、c、结果;
char-op[2];
//从用户输入中获取数字和数学运算符
cin>>a>>op[0]>>b>>op[1]>>c;
result=a op[0]b op[1]c;//如果op[0]=+和op[1],则result=a+b-c=-
//输出结果
cout您的逻辑错误。在第一个switch语句中,您设置了result=a OP1 b
。在第二个switch语句中,您设置了result=b OP2 c
,完全覆盖了第一个switch所做的操作。相反,您必须处理中间结果,例如,将第二个switch更改为
switch(operation2)
{
case '+':
result = result + c;
break;
case '-':
result = result - c;
break;
case '*':
result = result * c;
break;
case '/':
result = result / c;
break;
default:
cout << "Invalid operation. Program terminated." << endl;
return -1;
}
开关(操作2)
{
格“+”:
结果=结果+c;
打破
案例'-':
结果=结果-c;
打破
案例“*”:
结果=结果*c;
打破
案例“/”:
结果=结果/c;
打破
违约:
你难道没有注意到这甚至无法编译吗?如果switch
使用两个数字,为什么不在这里使用例如switch
来处理三个数字??
switch(operation2)
{
case '+':
result = result + c;
break;
case '-':
result = result - c;
break;
case '*':
result = result * c;
break;
case '/':
result = result / c;
break;
default:
cout << "Invalid operation. Program terminated." << endl;
return -1;
}