• 循环-17. 简单计算器(20)


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

    输入格式:

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

    输出格式:

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

    输入样例:
    1+2*10-10/2=
    输出样例:
    10

    #include <iostream>
    #include <stdio.h>
    #include <math.h>
    #include<string>
    double compute(char c,double op1,double op2)
    {
    	if(c=='+') return op1+op2;
    	else if(c=='-') return op1-op2;
    	else if(c=='*') return op1*op2;
    	else 
    	{
    		return op1/op2;
    	} 
    }
    // 123+456/2=
    // 用123作为result,+作为lastop,等到第二个操作数temp=456,
    //等遇到/,将123+456计算出来,作为result,/作为lastop
    // 检测到=,就将最后一次的结果计算出来 
    
    int main(){
        double result;
        char c;
        double temp=0;
    	char lastop='+';
    
        while((c=getchar())!='=')
        {
        	if(c>='0'&&c<='9')
        	{
             temp=10*temp+c-'0';		
        	}
        	else if(c=='+')
        	{
        		if(lastop=='/'&&temp==0)
        		{
        			printf("ERROR");
        	     	return 0;
        		}
        	    else
    		   {
    		    result=compute(lastop,result,temp);
    	       }  
    		   lastop='+';
    		   temp=0;   
        	}
        	else if(c=='-')
        	{
        		if(lastop=='/'&&temp==0)
        		{
        			printf("ERROR");
        	     	return 0;
        		}
        	    else
    		   {
    		    result=compute(lastop,result,temp);
    	       }  
    		   lastop='-';
    		   temp=0;   
        	}
        	else if(c=='*')
        	{
        		if(lastop=='/'&&temp==0)
        		{
        			printf("ERROR");
        	     	return 0;
        		}
        	    else
    		   {
    		    result=compute(lastop,result,temp);
    	       }  
    		   lastop='*';
    		   temp=0;   
        	}
        	else if(c=='/')
        	{
        		if(lastop=='/'&&temp==0)
        		{
        			printf("ERROR");
        	     	return 0;
        		}
        	    else
    		   {
    		    result=compute(lastop,result,temp);
    	       }  
    		   lastop='/';
    		   temp=0;   
        	}
        	else if(c==' ')
        	{
        		
        	}
    		else
    		{
        	   printf("ERROR");
        	   return 0;
        	}
        }
        
        
        if(lastop=='/'&&temp==0)
        {
        		printf("ERROR");
        	    return 0;
       	}
        else
    	{
    		    result=compute(lastop,result,temp);
    	}  
        printf("%d",(int)result);
        return 0;
    }
    

      

  • 相关阅读:
    c#中MessageBox的使用(转)
    ArcGIS中地图配准(转)
    VS2010中VC9.0Runtime与VC10.0Runtime在win7上装不上提示error code 1603(转)
    win7下安装Oracle 10G 的成功方法
    解决win 7 下打不开chm格式文件的办法
    vi 编辑器
    开源赚钱思路
    如何开始linux 编程
    Linux C语言开发基础
    如何做开源项目——ABC
  • 原文地址:https://www.cnblogs.com/ligen/p/4248546.html
Copyright © 2020-2023  润新知