- 題目描述:
-
讀入一個只包含 +, -, *, / 的非負整數計算表達式,計算該表達式的值。
- 輸入:
-
測試輸入包含若干測試用例,每個測試用例佔一行,每行不超過200個字符,整數和運算符之間用一個空格分隔。沒有非法表達式。當一行中只有0時輸入結束,相應的結果不要輸出。
- 輸出:
-
對每個測試用例輸出1行,即該表達式的值,精確到小數點後2位。
- 樣例輸入:
-
1 + 2
4 + 2 * 5 - 7 / 11
0
- 樣例輸出:
-
3.00
13.36
/*該題要特別注意輸入格式*/
#include <stdio.h>
#include<stack>
using namespace std;
int main()
{
stack<double> s;
char c1,c2;
int d;
//注意加一個空格對應數字之後的空格
while(scanf("%d ", &d)!=EOF && d!=0) {
s.push(d);
//%c %d%c 分別接受字符、字符後的空格、數字、字符。
//若判斷最後一個字符不爲空格,則說明輸入結束
while( scanf("%c %d%c", &c1,&d,&c2)) {
if(c1 == '+') {
s.push(d);
}else if(c1 == '-'){
s.push(-d);
}else if(c1 == '*') {
double tmp = s.top() * d;
s.pop();
s.push(tmp);
}else if(c1 == '/') {
double tmp = double(s.top() / d);
s.pop();
s.push(tmp);
}
if(c2 != ' ') break; //表達式輸入結束
}
while(!s.empty()) {
if(s.size() == 1) {
double r = s.top();
s.pop();
printf("%.2lf\n", r);
}else {
double a,b,c;
a = s.top();
s.pop();
b = s.top();
s.pop();
c = a + b;
s.push(c);
}
}
}
return 0;
}