HDU 1237 (simple calculator)

Each read into a digital and an operator, divided in two categories:

  1. If the read to the '*', then the number of the last read current multiplication, and the result is stored in the original location; '/' Similarly.
  2. If the read to the '+' operator precedence because of problems need to store the digital read together; '-' Similarly, the inverse of the digital storage.

Read until the character '\ n' represents the end of the reading, all stored numbers can be summed.

#include <cstdio>

int main()
{
    double num[100]; //存储数字的数组
    while (scanf("%lf", &num[0]) == 1)
    {
        double ans = 0; //结果
        char op = getchar(); //运算符
        if (num[0] == 0 && op == '\n') //只有0
            break;

        int i = 0;
        double temp;
        while (scanf("%c %lf", &op, &temp) == 2)
        {
            if (op == '*')
                num[i] *= temp;
            else if (op == '/')
                num[i] /= temp;
            else if (op == '+')
                num[++i] = temp;
            else
                num[++i] = -temp;

            op = getchar(); //读取空格或者换行符
            if (op == '\n') //换行符则结束
                break;
        }
        while (i >= 0) //所有存储的数字相加
        {
            ans += num[i];
            i--;
        }
        printf("%.2f\n", ans);
    }
    return 0;
}

Keep up.

 

Published 152 original articles · won praise 1 · views 7593

Guess you like

Origin blog.csdn.net/Intelligence1028/article/details/104709958