目录
1.加减乘除的前缀表达式求值
问题描述
输入带空格的前缀表达式求其值
样例
输入:
+ 3 4 |
输出:
7 |
所用知识
1.函数递归。
2.stringstream对象取子串。stringstream对象能取出被空格隔开的子串。
代码
#include<iostream>
#include<sstream>
#include<stdlib.h>
using namespace std;
double f(stringstream &s)
{
string w;
s>>w;
if(w=="+")return f(s)+f(s);
else if(w=="-")return f(s)-f(s);
else if(w=="/")return f(s)/f(s);
else if(w=="*")return f(s)*f(s);
else return atoi(w.c_str());
}
int main()
{
char a[100];
cin.getline(a,100);
stringstream s(a);
cout<<f(s);
return 0;
}
运行结果
2.加、减、乘、除、平方、取反的前缀表达式求值
问题描述
自定义运算函数如:add(加),sub(减),mult(乘),div(除以),neg(取反),doubleMe(平方)求前缀表达式的值。
样例
输入:
add sub neg 4 12 mult doubleMe 2 5 |
输出:
4 |
所用知识
1.函数递归。
2.stringstream对象取子串。stringstream对象能取出被空格隔开的子串。
代码
#include<iostream>
#include<sstream>
#include<stdlib.h>
#include<cmath>
#include"windows.h"
using namespace std;
double f(stringstream &s)
{
string w;
s>>w;
if(w=="add")return f(s)+f(s);
else if(w=="sub")return f(s)-f(s);
else if(w=="div")return f(s)/f(s);
else if(w=="mult")return f(s)*f(s);
else if(w=="neg")return -f(s);
else if(w=="doubleMe")return pow(f(s),2);
else return atoi(w.c_str());
}
int main()
{
char a[1000];
cin.getline(a,1000);
stringstream s(a);
cout<<f(s)<<endl;
return 0;
}
运行结果
欢迎指正!