简体   繁体   English

如何从输入中提取?

[英]How to extract from input?

How do you calculate, given that the input is as follows?假设输入如下,你如何计算?

All the questions are in the format of You also took note that all the numbers were positive integers and there were only 3 types of operators: +, - and *.所有的问题都是格式你还注意到所有的数字都是正整数,只有3种运算符:+、-和*。

Sample Input 1样本输入 1

5 - 3 5 - 3

Sample Output 1示例输出 1

2 2

Sample Input 2样本输入 2

7 * 7 7*7

Sample Output 2示例输出 2

49 49

Sample Input 3样本输入 3

13 + 4 13 + 4

Sample Output 3示例输出 3

17 17

You are tasked to write a calculator in https://en.wikipedia.org/wiki/Reverse_Polish_notation .您的任务是在https://en.wikipedia.org/wiki/Reverse_Polish_notation 中编写一个计算器。 There are many tutorials on the web on how to do this.网上有很多关于如何做到这一点的教程。

Well, since you have no requirements in regards to implementation, a simple switch statement would do.好吧,由于您对实现没有要求,一个简单的switch 语句就可以了。 Here's a simple example implementation.这是一个简单的示例实现。 If you are new to C++, note down std::cerr .如果您不std::cerr C++,请记下std::cerr

#include <iostream>
#include <cstdlib>

int main()
{
  int a, b;
  char op;
  std::cin >> a >> op >> b;
  switch (op)
  {
    case '+':
    {
      std::cout << a + b << std::endl;
      break;
    }
    case '-':
    {
      std::cout << a - b << std::endl;
      break;
    }
    case '*':
    {
      std::cout << a * b << std::endl;
      break;
    }
    default:
    {
      std::cerr << "Invalid operator" << std::endl;
      return EXIT_FAILURE;
    }
  }
  return EXIT_SUCCESS;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM