蓝桥杯基础 算法训练 前缀表达式 (基础语法)

问题描述

  编写一个程序,以字符串方式输入一个前缀表达式,然后计算它的值。输入格式为:“运算符 对象1 对象2”,其中,运算符为“+”(加法)、“-”(减法)、“*”(乘法)或“/”(除法),运算对象为不超过10的整数,它们之间用一个空格隔开。要求:对于加、减、乘、除这四种运算,分别设计相应的函数来实现。
  输入格式:输入只有一行,即一个前缀表达式字符串。
  输出格式:输出相应的计算结果(如果是除法,直接采用c语言的“/”运算符,结果为整数)。
  输入输出样例

样例输入

+ 5 2

样例输出

7

 

#include<iostream>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<algorithm>
#include<map>
#include<cmath>
using namespace std;

int add(int a,int b)
{
	return a+b;
}

int sub(int a,int b)
{
	return a-b;
}

int mul(int a,int b)
{
	return a*b;
}

int di(int a, int b)
{
	return a/b;
}

int main()
{
	char ch;
	int a,b;
	while (cin>>ch)
	{
		
		cin>>a>>b;
		if (ch=='+')
		cout<<add(a,b)<<endl;
		else if (ch=='-')
		cout<<sub(a,b)<<endl;
		else if (ch=='*')
		cout<<mul(a,b)<<endl;
		else
		cout<<di(a,b)<<endl;
	}
	
	
	return 0;
}

 

posted @ 2019-02-06 11:16  RomanticChopin  阅读(169)  评论(0编辑  收藏  举报
-->
Live2D