九度OJ 1019:简单计算器 (基础题、DP)

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:6725

解决:2454

题目描述:
    读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
    测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
    对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
1 + 2
4 + 2 * 5 - 7 / 11
0
样例输出:
3.00
13.36
来源:
2006年浙江大学计算机及软件工程研究生机试真题

思路:

可以用动态规划的思路来做。保存两个数和中间的计算符,逐步向后推进即可。

据说用栈做这个题效果也不错。


代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
#define M 200
 
int isnumber(char c)
{
    return ('0' <= c && c <= '9');
}
 
double compute(double a, char op, double b)
{
    switch(op)
    {
    case '+':
        return a+b;
    case '-':
        return a-b;
    case '*':
        return a*b;
    case '/':
        return a/b;
    }
}
 
void combine(double *a, char *op, double *b, char opnew, double c)
{
    if (opnew == '+' || opnew == '-')
    {
        *a = compute(*a, *op, *b);
        *op = opnew;
        *b = c;
    }
    else
        *b = compute(*b, opnew, c);
}
 
int main(void)
{
    char s[M+1], tmp[M+1];
    int i, j;
    double a, b, c;
    char op, opnew;
    double res;
 
    while (gets(s))
    {
        if (strcmp(s, "0") == 0)
            break;
 
        a = 0.0;
        b = 0.0;
        op = '+';
        i = 0;
        while (s[i])
        {
            if (i != 0)
            {
                i++;
                opnew = s[i++];
                i++;
            }
            else
                opnew = '+';
            j = 0;
            while (isnumber(s[i]))
                tmp[j++] = s[i++];
            tmp[j] = '\0';
            c = atoi(tmp);
            combine(&a, &op, &b, opnew, c);
        }
        res = compute(a, op, b);
        printf("%.2lf\n", res);
    }
 
    return 0;
}
/**************************************************************
    Problem: 1019
    User: liangrx06
    Language: C
    Result: Accepted
    Time:0 ms
    Memory:912 kb
****************************************************************/


posted on 2015-10-16 19:50  梁山伯  阅读(326)  评论(0编辑  收藏  举报

导航