一个简单的计算器

//calculate.c
//将运算数和运算符保存在两组数组里面
//如果碰到乘法和除法直接算出来,运算符数组里面只保存加法和减法 
//最后算加减法 
#include<stdio.h>
void yunsuan();

int main()
{
    printf("这个程序只支持加减乘除运算!支持运算优先级!\n\n");
    
    yunsuan();

    return 0;
}

void yunsuan()
{
    double number[100];
    char fuhao[100];
    double total = 0;
    double temp;
    char ch;
    int index1 = 0;
    int index2 = 0;
    int i = 0;

    while(scanf("%lf", &temp) == 0){}	//强制输入运算数 
    number[index1] = temp;
    
    while(scanf("%c", &ch) == 0){}		//强制输入运算符号 
    
    while(i != 1 )
  	switch(ch){
       	case '+':
           fuhao[index2++] = ch;
           while(scanf("%lf", &temp) == 0){}
            number[++index1] = temp;    
            while(scanf("%c", &ch) == 0){}
            break;
       	case '-':
            fuhao[index2++] = ch;
            while(scanf("%lf", &temp) == 0){}
            number[++index1] = temp;
            while(scanf("%c", &ch) == 0){}
            break;
        case '*':
            while(scanf("%lf", &temp) == 0){}
            number[index1] *= temp;
            while(scanf("%c", &ch) == 0){}
            break;
        case '/':
            while(scanf("%lf", &temp) == 0){}
            number[index1] /= temp;
            while(scanf("%c", &ch) == 0){}
            break;
        case '=':
            i = 1;
            break;
        default:
            scanf("%c", &ch);
            break;
   	}
    
    total = number[0];
    if(fuhao[0] != 0)
        for(int i = 0; i <= index2; i++)
            switch(fuhao[i]){
                case '+':
                    total += number[++i];
                    break;
                case '-':
                    total -= number[++i];
                    break;
                default:
                    break;
            }
    
	if(total > (int)total)      
    	printf("结果等于  %f.\n", total);
    else
    	printf("结果等于  %d.\n", (int)total);
    printf("\n");
    
    printf("右上角退出!\n");
    yunsuan();
} 

 

阅读更多

没有更多推荐了,返回首页