您的位置:首页 > 其它

一个简单的计算器程序

2010-01-04 15:20 423 查看
前段时间写了一个简单的计算器程序,可以支持+-*/()和数字构成的表达式,每个表达式以分号结束,运行时向下面这样:



$ ./a.out 
(2+3)*(-2+5);
15.000


有兴趣的可以编译后玩玩,源代码如下:

#include <stdio.h>
#include <stdlib.h>
#define NONE -1
enum {NUM=256};
int lookahead;
double token_val;
int get_token()
{
    int t;
    while(1){
        t = getchar();
        if(t == ' ' || t == '/t')
            ;
        else if( t == '/n')
            ;
        else if (isdigit(t)){
            ungetc(t, stdin);
            scanf("%lf", &token_val);
            return NUM;
        }else if ( t == EOF)
            return t;
        else{
            token_val = NONE;
            return t;       //operators, parenthesis etc.
        }
    }
}
void match(int type)
{
    if(lookahead == type)
        lookahead = get_token();
    else
        printf("syntax error/n");
}
double term();
double factor();
double expr()
{
    double left = term();
    while(1){
        if(lookahead == '+'){
            match('+');
            left += term();
        }else if(lookahead =='-'){
            match('-');
            left -= term();
        }else
            return left;    //lookahead not for expr, return current value.
    }
}
double term()
{   
    double left = factor();
    while(1){
        if(lookahead == '*'){
            match('*');
            left *= factor();
        }
        else if(lookahead =='/'){
            match('/');
            double right = factor();
            if(right) 
                left /= right;
            else{
                printf("divided by zero!/n");
                exit(0);
            }
        }else
            return left;    //lookahead not for term, return current value.
     
    }
}
double factor()
{
    double left;
    if(lookahead == '('){
        match('(');
        left = expr();
        match(')');
    }else if(lookahead == NUM){
        left = token_val;
        match(NUM);
    }else if(lookahead == '-'){
        match('-');
        left = -factor();
    }
    else{
        printf("error: what's this?/n");
        exit(0);
    }
    return left;
}
int main()
{   
    lookahead = get_token();
    while(lookahead != EOF) {
        printf("%.3lf/n", expr());
        match(';');       //end this expr
    }
    
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: