-3
所以我试图让一个计算器与多个运算符一起工作。我制作了一些计算器程序,使用2个数字(使用开关),但是当我尝试使用2个以上的数字时,我无法真正使其工作。我有一个想法如何做到这一点,但我不能实现它(我是编程新手)。这行不行,但这是我的想法:result = a op [0] b op [1] c; 因此,这里的代码:C++多个运算符计算器
// 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;
}
这里的其他代码,但不工作
// CalculatorSwitch.cc
// Simple arithmetic calculator using switch() selection.
#include <iostream>
using namespace std;
int main()
{
float a, b, c, result;
char operation,operation2;
// Get numbers and mathematical operator from user input
cin >> a >> operation >> b >> operation2 >> c;
// Character constants are enclosed in single quotes
switch(operation)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a/b;
break;
default:
cout << "Invalid operation. Program terminated." << endl;
return -1;
}
switch(operation2)
{
case '+':
result = b + c;
break;
case '-':
result = b - c;
break;
case '*':
result = b * c;
break;
case '/':
result = b/c;
break;
default:
cout << "Invalid operation. Program terminated." << endl;
return -1;
}
}
所以,如果我是正确的,以超过2个号码使用它,我必须创建一个第二开关第二个操作符,但我得到了错误的结果..所以我想让第一个代码工作。
你没有注意到,这甚至不会编译? –
如果'switch'使用两个数字,为什么不使用例如这里开关三个数字? – SaschaP