zoukankan      html  css  js  c++  java
  • C

    - 题目大意

        给出一个四则运算计算式,然后来求值。

    - 解题思路

        根据符号来利用栈将数变换成对应的形式,比如如果是’+’的话,便将后面的那个数字压入栈中,’-‘号的话,将后面的数字取反压入栈中,而如果遇到乘法或除法,则将栈顶取出与符号后面的数字计算后压入栈中,这样最后在栈中的数字全部相加即是表达式的值了。

    - 代码

    #include<iostream>
    #include<stack>
    #include<iomanip>
    using namespace std;
    
    int main()
    {
    
    	double a, b,temp;
    	double s = 0.00;
    	char c;
    	stack<double>sum;
    	while (cin >> a)
    	{
    		c = getchar();
    		if (c == '
    '&&a == 0)
    			break;
    		sum.push(a);
    		while (cin>>c>> b)
    		{
    			if (c == '*')
    			{
    				temp = sum.top();
    				sum.pop();
    				sum.push(temp * b);
    			}
    			else if (c == '/')
    			{
    				temp = sum.top();
    				sum.pop();
    				sum.push(temp / b);
    			}
    			 
    			else if (c == '+')
    			{
    				sum.push(b);
    			}
    			else if(c == '-')
    			{
    			    sum.push(-b);
    			}
    			if (getchar() == '
    ')
    				break;
    		}
    		while (!sum.empty())
    		{
    			s += sum.top();
    			sum.pop();
    		}
    		cout << setprecision(2) << std::fixed << s << endl;
    		s = 0;
    	}
    	
    	return 0;
    	
    }
    

      

  • 相关阅读:
    Linux中的邮件发送
    Python学习笔记18-发送邮件
    Ansible学习笔记
    eclipse使用maven打包时去掉测试类
    CentOS安装redis
    spring boot 部署
    sprint boot 配置
    spring-boot 学习笔记一
    不要容忍破窗户
    阿里云安装Oracle
  • 原文地址:https://www.cnblogs.com/alpacadh/p/8438493.html
Copyright © 2011-2022 走看看