- 總Time Limit:
- 1000ms
- Memory Limit:
- 65536kB
- Description
- 逆波蘭表達式是一種把運算符前置的算術表達式,例如普通的表達式2 + 3的逆波蘭表示法爲+ 2 3。逆波蘭表達式的優點是運算符之間不必有優先級關係,也不必用括號改變運算次序,例如(2 + 3) * 4的逆波蘭表示法爲* + 2 3 4。本題求解逆波蘭表達式的值,其中運算符包括+ - * /四個。
- Input
- 輸入爲一行,其中運算符和運算數之間都用空格分隔,運算數是浮點數。
- Output
- 輸出爲一行,表達式的值。
可直接用printf("%f\n", v)輸出表達式的值v。 - Sample Input
-
* + 11.0 12.0 + 24.0 35.0
- Sample Output
-
1357.000000
- Hint
- 可使用atof(str)把字符串轉換爲一個double類型的浮點數。atof定義在math.h中。
此題可使用函數遞歸調用的方法求解。
-----------------------------------------------------------------------------
遞歸題,將輸入也放入遞歸的過程中將降低難度
(代碼參考《程序設計導引及在線實踐》)
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include "math.h"
using namespace std;
char s[100];
double cal()
{
cin>>s;
if (s[0]>='0'&&s[0]<='9')
return atof(s);
else
{
if(s[0] == '+')
return cal() + cal();
else if(s[0] == '-')
return cal() - cal();
else if(s[0] == '*')
return cal() * cal();
else if(s[0] == '/')
return cal() / cal();
}
}
int main()
{
printf("%f",cal());
return 0;
}