PTA02 简单计算器

简单计算器(20 分)

模拟简单运算器的工作。假设计算器只能进行加减乘除运算,运算数和结果都是整数,四种运算符的优先级相同,按从左到右的顺序计算。

输入格式:

输入在一行中给出一个四则运算算式,没有空格,且至少有一个操作数。遇等号”=”说明输入结束。

输出格式:

在一行中输出算式的运算结果,或者如果除法分母为0或有非法运算符,则输出错误信息“ERROR”。

输入样例:

1+2*10-10/2=

输出样例:

10

方法1:

  1. #include"stdio.h"  
  2. int main()  
  3. {  
  4.     int value1,value2;  
  5.     int sum=0;  
  6.     char ch;  
  7.     scanf("%d",&value1);  
  8.     while((ch=getchar())!='=')  
  9.     {  
  10.         scanf("%d",&value2);  
  11.         if(ch=='/'&&value2==0){  
  12.                 printf("ERROR\n");  
  13.                 return 0;  
  14.   
  15.         }  
  16.         switch(ch)  
  17.         {  
  18.             case '+':sum=value1+value2;break;  
  19.             case '-':sum=value1-value2;break;  
  20.             case '*':sum=value1*value2;break;  
  21.             case '/':sum=value1/value2;break;  
  22.             default:printf("ERROR\n");return 0;  
  23.   
  24.         }  
  25.         value1=sum;  
  26.   
  27.   
  28.     }  
  29.     printf("%d\n",value1);  
  30.     return 0;  

方法2:

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int i,sum,isnan=0;  
  5.     char op='0';//运算符初始值为'0'   
  6.     scanf("%d",&sum);  
  7.     while(op!='=')  
  8.     {  
  9.         scanf("%c",&op);  
  10.         if(op=='=')  
  11.             break;  
  12.           
  13.         scanf("%d",&i);  
  14.         if(op=='+')  
  15.             sum=sum+i;//题目要求不考虑计算优先级,可以直接从左到右顺序计算   
  16.         else if(op=='-')//所以可以依次判断运算符,将新输入变量加到原来的结果上   
  17.             sum=sum-i;  
  18.         else if(op=='*')  
  19.             sum=sum*i;  
  20.         else if(op=='/'){//判断除法除数是否合法   
  21.             if(i!=0)//判断不为零的情况,而不是判断为零的情况   
  22.                 sum=sum/i;  
  23.             else  
  24.                 //printf("ERROR");  
  25.                 isnan=1;//设置判断点,输出时判断后输出   
  26.         }  
  27.         else  
  28.             isnan=1;//输入除了+ —* / 之外的符号,视为非法错误输入   
  29.         //printf("ERROR");  
  30.     }  
  31.     if(isnan==1)  
  32.         printf("ERROR");  
  33.     else  
  34.         printf("%d\n",sum);   
  35.     return 0;  
  36.       

猜你喜欢

转载自blog.csdn.net/luran_lz/article/details/80085550
今日推荐