思路:一开始我也不会写,最主要的就是不好分辨运算符的优先级。最后我去网上参考了别人的代码,然后自己顺着别人的思路想了想,就有了一下的代码!

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
using namespace std;

const int maxn = 201;
char s[maxn];
int p, l;

double get()                //先算a*b或者a/b的值.     
{
    double a, b;
    char opt;
    a = 0.0;
    while(isdigit(s[p]))
    {
        a *= 10;
        a += s[p++] -'0';
    }    
    p++; //跳过空格 
    while(p < l && (s[p] == '*' || s[p] == '/'))   //可能有多个'*' 
    {
        opt = s[p++];
        p++;               //跳过空格 
        b = 0.0;
        while(p < l && isdigit(s[p]))
        {
            b *= 10;
            b += s[p++] - '0';
        }
        p++;
        if(opt == '*')
        {
            a *= b;
        }
        else
        {
            a /= b;
        }
    }
    return a;
}               //这表达式只算a*b或者a/b的值,a+b或者a-b的值在递归调用是才算。


int main()
{
    double a, b;
    char opt;
    while(gets(s) && strcmp(s, "0"))
    {
        l = strlen(s);
        p = 0;
        a = get();
        while(p < l)
        {
            opt = s[p++];
            p++; //跳过空格
            b = get();                     //求得下一个运算符的位置以及表达式中a*b或者a/b的值。
            if(opt == '+'//a+b 
            {
                a += b;
            } 
            else         //a-b
            {
                a -= b;
            }
        }
        printf("%.2lf\n", a);
    }
    return 0;

 

posted on 2012-07-21 16:31  有间博客  阅读(398)  评论(0)    收藏  举报