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


    b22bb5b7

     1/**********************************
     2题目:波兰式计算器
     3/* 以下是几个标准的表达式:
     45 * 2 + -3
     55 * (2 + -3)
     65 + ((-4 * -5) + (((5 + (6 - 2)) * 7 + ((4 + 2) * (3 - 1))))
     7与之等价的波兰表达式为
     8+ * 5 2 -3
     9* 5 + 2 -3
    10+ 5 + * -4 -5 + * + 5 - 6 2 7 * + 4 2 - 3 1
    11
    12Author:Linghucong
    13Date:2007-4-28
    14***********************************/

    15#include <math.h>
    16#include <stdio.h>
    17#include <string>
    18#include <iostream>
    19using namespace std;
    20
    21void Polan(string test)  {
    22    string ops[100];
    23    int opNum = -1;
    24    int i = 0;
    25    while (i < test.length())
    26    {
    27        //处理空格
    28        if (test[i] == ' '{
    29            i++;
    30            continue;
    31        }

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

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

    42        }

    43        string str = test.substr(i, count);
    44        i += count;
    45        ops[++opNum] = str;
    46
    47        int res;
    48        //算法:加入一个数字之后检查其前面一个值是不是数字,如果是,则计算,如果不是,继续往数组中添加值。
    49        while (opNum > 1 && ops[opNum - 1!= "+" && ops[opNum - 1!= "*" && ops[opNum - 1!= "-"{
    50            if (ops[opNum - 2== "+"{
    51                res = atoi(ops[opNum].c_str()) + atoi(ops[opNum - 1].c_str()) ;
    52                opNum -= 2;
    53            }
     else if(ops[opNum - 2== "-"{
    54                res = atoi(ops[opNum - 1].c_str()) - atoi(ops[opNum].c_str());
    55                opNum -= 2;
    56            }
     else if(ops[opNum - 2== "*"{
    57                res = atoi(ops[opNum].c_str()) * atoi(ops[opNum - 1].c_str());
    58                opNum -= 2;
    59            }

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

    65        }

    66    }

    67
    68    cout << ops[0<< endl;
    69}

    70

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

  • 相关阅读:
    VS2010中使用JSONCPP方法
    VC获取外网IP
    JSON样例
    JSON详解
    vc获取本地IP
    Java中创建对称密钥的代码
    密和解密程序的一些概念
    在ireport报错 报 jdk5找不到的解决办法
    Java中创建对称密钥的步骤
    比较好用的一个jaspereport模板 生成html页面模板
  • 原文地址:https://www.cnblogs.com/jiji262/p/732722.html
Copyright © 2020-2023  润新知