c++多运算符计算器
c++ multiple operators calculator
所以我正在尝试制作一个可以使用多个运算符的计算器。我制作了一些计算器程序,可以使用2个数字(使用开关),但当我尝试使用2个以上的数字时,我无法真正使其工作。我有一个想法,但我无法实现它(我是编程新手)。这一行不起作用,但这就是我的想法:result=a op[0]b op[1]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语句中,您设置了result = a OP1 b
。在第二个开关中,您设置了result = b OP2 c
,完全覆盖了第一个开关的操作。相反,你必须处理中间结果,例如,将第二次切换到
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;
}
然而,请注意,这仍然是不正确的,因为如果第一个运算符是+
或-
,而第二个运算符是*
或/
,它会忽略操作顺序。
要使第一个代码发挥作用,需要的不仅仅是这个答案,创建一个完整的数学解析器绝非易事。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- C++计算器运算符
- RPN计算器c++错误处理和多个运算符
- 实现 =, - =, *=, /=运算符(复杂号码控制器计算器)
- 长方程加法/减法计算器,从文本文件中提取运算符和数字
- 在 c++ 计算器程序中重载 '+' 运算符时无法获得正确的输出
- 如何在boost::精神计算器中添加对指数运算符的支持
- 关于分数计算器的运算符重载
- c++多运算符计算器