2013-06-13 07:31:33Morris
[UVA][字串分析] 11070 - The Good Old Times
The good old times
In the stoneage things weren't as easy for programmers as they are today. For example programmers had only very slow computers with a very limited main memory and very small hard disks at their disposal. Furthermore a lot of standard applications hadn't been developed. Now one of your customers, Fred Flintstone, wants a command line calculator for his computer, the new Granite500 with 1000 hertz. Your task is to write a command line calculator for him.
Input
Each line of input will consist of a string of length l, l < 255, containing a valid arithmetic expression. Because main memory was very small in those days, the string will contain no blanks or tabs, nor parathensis. It will contain the four standard arithmetic operators +,-,*,/ as well as a unary - or + and floating point numbers. The input will be terminated by EOF.Output
For each line of input, output the value of the arithmetic expression on a single line. The result should contain three digits after the decimal point.Hint: use double
Sample Input
1/2/2 -3.0 3 4.0+3.0/5.0 1*2*3+1+1*2+1*2*3*4
Sample Output
0.250 -3.000 3.000 4.600 33.000
FAU Local Contest 2004-07-10
Author: Tilmann Spiegelhauer
沒有括弧就比較簡單些。可以利用遞迴解決。
不過有可能會有多個一元運算,如 ---+-9 之類的鬼東西。
題目描述還真看不出來。
#include <stdio.h>
#include <string.h>
int i = 0;
char s[5000];
double sol(double flip) {
double h, g;
double unary = 1;
while(s[i] == '-' || s[i] == '+') {
if(s[i] == '-') unary = -unary;
i++;
}
sscanf(s+i, "%lf", &h);
h *= unary;
while((s[i] >= '0' && s[i] <= '9') || s[i] == '.')
i++;
if(s[i] == '+') {
i++;
return h*flip + sol(1);
}
if(s[i] == '-') {
i++;
return h*flip + sol(-1);
}
if(s[i] == '\0') return h*flip;
char pre = s[i];
do {
i++;
unary = 1;
while(s[i] == '-' || s[i] == '+') {
if(s[i] == '-') unary = -unary;
i++;
}
sscanf(s+i, "%lf", &g);
g *= unary;
while((s[i] >= '0' && s[i] <= '9') || s[i] == '.')
i++;
if(pre == '*')
h *= g;
if(pre == '/')
h /= g;
if(s[i] == '\0') return h*flip;
if(s[i] == '+') {
i++;
return h*flip + sol(1);
}
if(s[i] == '-') {
i++;
return h*flip + sol(-1);
}
pre = s[i];
} while(true);
puts("err");
return 0;
}
int main() {
while(scanf("%s", &s) == 1) {
i = 0;
printf("%.3lf\n", sol(1)+1e-8);
}
return 0;
}