【问题标题】:How to add multi digit integers in a reverse polish calculator如何在逆波兰计算器中添加多位整数
【发布时间】:2014-12-07 14:00:41
【问题描述】:
    // FILE: calc.h
#include <iostream>
#include <stack> // Uses STL
#include <string> // Uses STL
using namespace std;

void evaluate_stack_tops(stack<double> & numbers, stack<char> & operations);

double read_and_evaluate(string line)
{
    const char RIGHT_PARENTHESIS = ')';
    stack<double> numbers; // local stack object
    stack<char> operations; // local stack object
    double number;
    char symbol;
    size_t position = 0;
    while (position < line.length())
    {

        if (isdigit(line[position]))
        {
            number = line[position++] - '0'; // get value
            numbers.push(number);
        }
        else if (strchr("+-*/", line[position]) != NULL)
        {
            symbol = line[position++];
            operations.push(symbol);
        }
        else if (line[position] == RIGHT_PARENTHESIS)
        {
            position++;
            evaluate_stack_tops(numbers, operations);
        }
        else
            position++;
    }
    if (!operations.empty())
        evaluate_stack_tops(numbers, operations);
    return numbers.top();
}

void evaluate_stack_tops(stack<double> & numbers, stack<char> & operations)
{
    double operand1, operand2;
    operand2 = numbers.top();
    numbers.pop();
    operand1 = numbers.top();
    numbers.pop();
    switch (operations.top())
    {
    case '+': numbers.push(operand1 + operand2); break;
    case '-': numbers.push(operand1 - operand2); break;
    case '*': numbers.push(operand1 * operand2); break;
    case '/': numbers.push(operand1 / operand2); break;
    }
    operations.pop();
}


// FILE: Use_Stack.cpp
#include <iostream>   
using namespace std;
#include "calc.h"

int main()
{
    double answer;
    string line;
    cout << "Type a fully parenthesized arithmetic expression (SINGLE DIGITS ONLY!):\n";
    getline(cin, line);
    answer = read_and_evaluate(line);
    cout << "That evaluates to " << answer << endl;
    system("pause");
    return 0;
}

一切正常,我可以输入“2 4 3 * + 7 – 2 +”之类的简单内容,但如果我想输入“123 60 +”之类的内容,它将无法正常工作。我把它分成两个头文件。有人可以给我一个关于如何接受多位整数的提示吗?

【问题讨论】:

标签: c++ stack calculator postfix-notation


【解决方案1】:

解决问题的一种方法是在哪里发现一个数字,而不是假设它只有一位长,而是使用循环来收集属于该数字的所有其他数字。当遇到非数字或空格时,循环将终止。

更好的方法是使用stringstream 标记输入字符串。在这种情况下,您会将整行输入放入一个字符串中,然后使用类似于以下内容的 while 循环:

stringstream ss(line);
string token;
while (ss >> token) {
    // do stuff with token
}

【讨论】:

  • 谢谢你,我会试试看!
【解决方案2】:

RPN 的工作原理是拥有一堆您可以操作的值。给定输入"13",从top=1top=13 所需的操作相当简单:top = 10 * top + digit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    相关资源
    最近更新 更多