http://www.1point3acres.com/bbs/thread-12175-1-1.html
如何写出一个简单的4则运算的程序。 输入 " 1 -2*3 + 6/3" 输出 -3 只用支持正数int的,+,-,*,/,不用写出()的情况 |
要注意的问题是,空格。。。。
可以直接用逆波兰式做,稍麻烦,用递归可以直接做
#include <iostream>
#include <cstdio>
using namespace std;
char c;
double num() {
double ret = 0;
while(c=getc(stdin)) {
if(c >= '0' && c <= '9')
ret = ret * 10 + c-'0';
else break;
}
double dec = 0.1;
if(c=='.') {
while(c=getc(stdin)) {
if(c >= '0' && c <= '9') {
ret += dec*(c-'0');
dec /= 10;
}
else break;
}
}
return ret;
}
double calc_mul()//返回下一个数字或者返回后面乘除的值
{
double ret = num();
while(c=='*'||c=='/') {
ret = c=='*'?ret*num():ret/num();
}
return ret;
}
double calc_add()
{
double ret = calc_mul();
while(c=='+'||c=='-') {
ret = c=='+'?ret+calc_mul():ret-calc_mul();
}
return ret;
}
int main() {
cout << calc_add() << endl;
return 0;
}
int cal(int last, int idx ) {//idx指向当前的运算符,last指前一个数字
if (idx >= n)
return last;
if (vt[idx] == "x")
return cal(last * atoi(vt[idx+1].c_str()), idx + 2);
if (vt[idx] == "/")
return cal(last / atoi(vt[idx+1].c_str()), idx + 2);
if (vt[idx] == "+")
{
if (idx + 2 >=N || vt[idx + 1] == "-" || vt[idx + 1] == "+")
return cal(last + atoi(vt[idx+1].c_str()), idx +2);
else
return last + cal(atoi(vt[idx+1].c_str()), idx +2);
}
//"-"同理
}