24h購物| | PChome| 登入
2013-06-13 07:31:33| 人氣642| 回應0 | 上一篇 | 下一篇

[UVA][字串分析] 11070 - The Good Old Times

推薦 0 收藏 0 轉貼0 訂閱站台


 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;
}

台長: Morris
人氣(642) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][math] 10854 - Number of Paths
此分類上一篇:[UVA][遞迴] 11291 - Smeech

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文