POJ2694逆波兰数

来源:互联网 发布:淘宝双115元红包怎么用 编辑:程序博客网 时间:2024/05/22 04:32
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

代码:

#include<stdio.h>#include<stdlib.h>double polan(){char s[10];scanf("%s",s);switch(s[0]){case '+':return polan()+polan();break;case '-':return polan()-polan();break;case '*':return polan()*polan();break;case '/':return polan()/polan();break;default:return atof(s);}}int main(){printf("%f\n",polan());return 0;}

输入数据后,输出逆波兰表达式的常规形式:

#include<stdio.h>#include<stdlib.h>char *polan(){char s[10];scanf("%s",s);switch(s[0]){case '+':printf("( "),polan(),printf("+"),polan(),printf(" )");break;case '-':printf("( "),polan(),printf("-"),polan(),printf(" )");break;case '*':printf("( "),polan(),printf("*"),polan(),printf(" )");break;case '/':printf("( "),polan(),printf("/"),polan(),printf(" )");break;default:printf("%s",s);return s;}}int main(){printf("%s\n",polan());return 0;}


0 0
原创粉丝点击