波兰式计算器程序(C++)

本文介绍了一个简单的波兰式计算器实现过程,通过逐步解析和算法优化,实现了对复杂表达式的正确计算。文章提供了完整的代码示例,并详细解释了如何处理操作符和数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写的时候才发现原来这么一个小程序也是这么的不容易,费了好办天劲,总发现算法只能满足大部分的情况,后来索性放下程序,仔细研究算法规律,突然发现,其实比想象中的要简单许多。在网上找到的代码有好几百行,简直不是人看的呵呵。发现自己的编程能力真的有待提高:》66dc3dd8

/**********************************
题目:波兰式计算器
/* 以下是几个标准的表达式:
5 * 2 + -3
5 * (2 + -3)
5 + ((-4 * -5) + (((5 + (6 - 2)) * 7 + ((4 + 2) * (3 - 1))))
与之等价的波兰表达式为
+ * 5 2 -3
* 5 + 2 -3
+ 5 + * -4 -5 + * + 5 - 6 2 7 * + 4 2 - 3 1

Author:Linghucong
Date:2007-4-28
**********************************
*/

#include 
<math.h>
#include 
<stdio.h>
#include 
<string>
#include 
<iostream>
using namespace std;

void Polan(string test)  {
    
string ops[100];
    
int opNum = -1;
    
int i = 0;
    
while (i < test.length())
    
{
        
//处理空格
        if (test[i] == ' '{
            i
++;
            
continue;
        }

        
//处理操作符
        if (test[i] == '+' || test[i] == '*' || (test[i] == '-' && test[i + 1== ' ')) {
            ops[
++opNum] = test[i++];
            
continue;
        }

        
//处理数字
        for (int count =0; count < test.length() - i; count++{
            
if (test[i + count] == ' '{
                
break;
            }

        }

        
string str = test.substr(i, count);
        i 
+= count;
        ops[
++opNum] = str;

        
int res;
        
//算法:加入一个数字之后检查其前面一个值是不是数字,如果是,则计算,如果不是,继续往数组中添加值。
        while (opNum > 1 && ops[opNum - 1!= "+" && ops[opNum - 1!= "*" && ops[opNum - 1!= "-"{
            
if (ops[opNum - 2== "+"{
                res 
= atoi(ops[opNum].c_str()) + atoi(ops[opNum - 1].c_str()) ;
                opNum 
-= 2;
            }
 else if(ops[opNum - 2== "-"{
                res 
= atoi(ops[opNum - 1].c_str()) - atoi(ops[opNum].c_str());
                opNum 
-= 2;
            }
 else if(ops[opNum - 2== "*"{
                res 
= atoi(ops[opNum].c_str()) * atoi(ops[opNum - 1].c_str());
                opNum 
-= 2;
            }


            _itoa(res, (
char *)ops[opNum].c_str(), 10);
            
if (opNum == 0{
                
break;
            }

        }

    }


    cout 
<< ops[0<< endl;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值