c++多运算符计算器

c++ multiple operators calculator

本文关键字:计算器 运算符 c++      更新时间:2023-10-16

所以我正在尝试制作一个可以使用多个运算符的计算器。我制作了一些计算器程序,可以使用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;
}

然而,请注意,这仍然是不正确的,因为如果第一个运算符是+-,而第二个运算符是*/,它会忽略操作顺序。

要使第一个代码发挥作用,需要的不仅仅是这个答案,创建一个完整的数学解析器绝非易事。