hdu 1237 简单计算器
Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
Sample Output
3.00 13.36递归加字符串、 定义的时候注意定义变量的位置, 因为位置不同,就会wa 别问我是怎么知道的,我试了好多次 代码: #include<stdio.h> #include<string.h> char str[1000]; int num; int k; double obtain(){ double a,b; char ch; a=0.0; // int k=0; while(str[k]>='0'&&str[k]<='9') a=a*10+(str[k++]-'0'); k++; while(k<num&&(str[k]=='*'||str[k]=='/')){ ch=str[k++]; k++; b=0.0; while(str[k]>='0'&&str[k]<='9') b=b*10+(str[k++]-'0'); k++; if(ch=='*') a*=b; if(ch=='/') a/=b; } return a; } int main(){ double a,b; char ch; // int k; // int i,j,k,t; while(gets(str),strcmp(str,"0")){ num=strlen(str); k=0; a=obtain(); while(k<num){ ch=str[k++]; k++; b=obtain(); if(ch=='+') a+=b; else a-=b; } printf("%.2lf\n",a); } return 0; }

浙公网安备 33010602011771号