【问题标题】:Simple Calculator Help (C++)简单计算器帮助 (C++)
【发布时间】:2014-03-16 12:55:28
【问题描述】:

我用 C++ 编写了一个非常简单的计算器程序,它运行良好!但是有人能解释一下我如何修改这段代码,使它能够一次添加两个以上的数字吗?

因此,例如,我希望用户能够执行 2 + 2 + 2,而不是执行 2 + 2。但每次我尝试时,它只会添加前两个“2”并给出 4,无论如何many + 2 你在它后面输入。

代码如下:

#include <iostream>

using namespace std;

// input function
void Input (float &x, float &y);

float a=1.0, b=1.0, result;
char operation;

int main ()
{
    cout << "A simple calculator \n\n";

    cin >> a >> operation >> b;

    Input (a,b);

    cout << result << endl;
    system ("pause");
    return 0;
}


void Input (float &x, float &y)
{
    a = x;
    b = y;

    switch (operation)
    {
    case '+':
        result = x + y;
    break;

    case '-':
        result = x - y;
    break;

    case '*':
        result = x * y;
    break;

    case '/':
        result = x / y;
    break;

    default:
        cout << "Improper operation. Please input a correct calculation        operation: \n";
        cin >> a >> operation >> b;
        Input (a, b);
    }
}

谢谢大家!

【问题讨论】:

  • 您没有读取超过 2 个数字和单个运算符的循环 - 为什么 operation 是全局而不是评估函数 Input 的参数?
  • 为什么你希望这段代码执行两次计算?您检索两个操作数和一个操作(cin >> a >> operation >> b)。向我们展示您尝试执行两次计算的代码。

标签: c++ calculator


【解决方案1】:

您的代码被认为是您要求输入三个元素:2 个数字及其运算符(表示为一个字符)。

假设您只拍摄一张照片。如果你想使用更多的运算符和数字,你必须开发一个简单的解析器,它应该继续获取输入,直到找到结束标记,在你的情况下可能是行结束。

为此,我会改变您关于数据采集和计算的方法。您必须选择简单的选项:

  • 在线执行计算:即保留部分结果并在每次输入后更新。
  • 将所有输入收集到一个表示它的数据结构中,然后执行所有计算。

例如,如果您决定实现第一个选项,那么这段不完整的代码可能会对您有所帮助:

float Input (float &x, float &y, char operation)
{
    float result;
    switch (operation)
    {
        case '+':
        result = x + y;
        break;

        case '-':
        result = x - y;
        break;

        case '*':
        result = x * y;
        break;

        case '/':
        result = x / y;
        break;

        default:
        cout << "Improper operation. Please input a correct calculation         operation: \n";

     }
     return result;
}

...
...

string input;
if(!getline( cin, input ) ) return; //Try to read one line.

istringstream lin( input );
float partial = 0.0;
float a;
char op;
while(lin >> op >> a) partial = Input(partial, a, op);


//At this point, partial should contain your final result

【讨论】:

    【解决方案2】:

    注意:我没有测试案例。就像除以零一样。等

    float operate(float a, char operand, float b)
    {
    
        float result=0.0;
    
        switch(operand)
        {
            case '+':
                result = (a+b);
                break;
    
            case '*':
                result = (a*b);
                break;
    
            case '/':
                result = (a/b);
                break;
    
            default:
                cout<<"Unknown operand"<<endl;
                break;
        }
    
    
        return result;
    
    }
    
    
    int main()
    {   
        float result=0.0;
        char operand;
        float a,b;
    
        cout<<"enter a number followed by an operation, followed by a number"<<endl;
    
    
        while(cin>>a>>operand>>b)
             result+=operate(a,operand,b);
    
        cout<<result;
    
        return 0;
    
    }
    

    【讨论】:

    • 如果你有奇数个数字怎么办?另一方面,您假设每个操作都添加到最终结果中。
    【解决方案3】:

    几周前我写了一个小解析器,你可以研究我的代码,也许(希望)你会发现一些有用的东西。
    它不是c++,而是c,所以你的编译器应该能够编译它。

    解析器解析任何可以通过以下规则构建的语句:

    <expression> ::= <term>
                   | <term> "+" <term>
                   | <term> "-" <term>
    
    <term>       ::= <factor>
                   | <factor> "*" <factor>
                   | <factor> "/" <factor>
    
    <factor>     ::= <number>
                   | "(" <expression> ")"
    
    <number>     ::= ["-"] ["0" .. "9"]*
    

    这里是代码,它几乎可以自我解释,因为它遵循上面定义的规则:

    #include <stdio.h>
    #include <stdlib.h>
    
    char next;
    
    void getNext(){
      next=getchar();
    }
    
    int getNum(){  //get a number
      int num=0;
      if((next<'0')||(next>'9')){
        printf("error: expected number; found %c",next);
        exit(-1);
      }
      while((next>='0')&&(next<='9')){
        num*=10;
        num+=(next-'0');
        getNext();
      }
      return num;
    }
    
    int add(int x){
      return x+term();
    }
    int sub(int x){
      return x-term();
    }
    int multiply(int x){
      return x*factor();
    }
    int divide(int x){
      return x/factor();
    }
    
    int factor(){
      int f=0;
      if(next=='('){
        getNext();
        f=expression();
        if(next=')')
          getNext();
        else{
          printf("error \")\" expected; found %c",next);
          exit(-1);
        }
      }else{
        f=getNum();
      }
      return f;
    }
    
    int term(){
      int val;
      val=factor();
      while((next=='*')||(next=='/')){
        char c=next;
        getNext();
        switch(c){
          case '*': val=multiply(val); break;
          case '/': val=divide(val); break;
          default: printf("error: (*, /) expected; found %c",next);
                   exit(-1);
        }
      }
      return val;
    }
    
    int expression(){
      int sign=1;
      int val;
      if(next=='-'){
        sign=-1;
        getNext();
      }
      val=term()*sign;
      while((next=='+')||(next=='-')){
        char c=next;
        getNext();
        switch(c){
          case '+': val=add(val); break;
          case '-': val=sub(val); break;
          default: printf("error: (+, -) expected; found %c",next);
                   exit(-1);
        }
      }
      return val;
    }
    
    int main(void) {
      getNext();
      printf("%d\n", expression());
      return 0;
    }
    

    示例:

    $ gcc main.c -o calc
    $ ./calc
    1+2+3           
    6
    $ ./calc
    (1+2+3)/2
    3
    $ ./calc
    3*(1+2)
    9
    $ ./calc
    -10+20
    10
    $
    

    【讨论】:

      猜你喜欢
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多