1. 程式人生 > >簡單計算器的編程【C++】

簡單計算器的編程【C++】

type suffix art iostream .net push 跳過 str else

第一篇博客嘎嘎

這篇是用棧去編程簡單計算器

關鍵詞:atoi()、memset()【https://blog.csdn.net/qq_27522735/article/details/53374765】、printf("%.2f\n", x)【保留兩位小數】

#include <iostream>

#include <cstdio>

#include <vector>

#include <stack>

#include <cstring>

#include <stdlib.h>

#include <stdio.h>

using namespace std;

struct stNode

{

int nType; //元素的類型,0操作數,1操作符

double nNum; //操作數

char cOp; //操作符

};

stack<char> sop; //運算符棧,用於中綴表達式轉換成後綴表達式

stack<double> sNum; //操作數棧,用於後綴表達式的計算

char cExp[1024]; //讀入的字符表達式

vector<stNode> SuffixExp; //後綴表達式

inline float GetNum(const char* p, int& k)

{

int n = atoi(p);

k = 0;

while (isdigit(p[k]))

++k;

return n;

}

inline int get_ip(char c) //獲取棧內優先級

{

switch (c)

{

case ‘#‘:

return 0;

case ‘+‘:

case ‘-‘:

return 3;

case ‘*‘:

case ‘/‘:

return 5;

}

return 99;

}

inline int get_op(char c) //獲取棧外優先級

{

switch (c)

{

case ‘#‘:

return 0;

case ‘+‘:

case ‘-‘:

return 2;

case ‘*‘:

case ‘/‘:

return 4;

}

return 99;

}

int main(void)

{

memset(cExp, 0, sizeof(cExp)); //初始化棧

while(cin.getline(cExp, 1024))

{

//讀入字符表達式

if(strlen(cExp)==1 && cExp[0]==‘0‘) break;

strcat(cExp, "#");

while (!sop.empty()) //清空操作符棧

sop.pop();

sop.push(‘#‘); //放入界定符

//將中綴表達式轉化成後綴表達式

char *p = cExp;

while (p[0] != ‘\0‘)

{

if (p[0] == ‘ ‘) //空格跳過

{

++p;

continue;

}

if (isdigit(p[0]))

{

//數字輸出到後綴表達式

int k;

double n = GetNum(p, k);

stNode stTemp;

stTemp.nType = 0;

stTemp.nNum = n;

stTemp.cOp = 0;

SuffixExp.push_back(stTemp);

p += k;

}

else

{

char ch1 = p[0];

char ch2 = sop.top();

if (get_op(ch1) > get_ip(ch2))

{

sop.push(ch1);

++p;

}

else if (get_op(ch1) < get_ip(ch2))

{

//輸出到後綴表達式

stNode stTemp;

stTemp.nType = 1;

stTemp.nNum = 0;

stTemp.cOp = ch2;

SuffixExp.push_back(stTemp);

sop.pop();

}

else

{

sop.pop();

++p;

}

}

}

//後綴表達式的計算

while (!sNum.empty()) //清空操作數棧

sNum.pop();

for (int i = 0; i < (int)SuffixExp.size(); ++i)

{

if (SuffixExp[i].nType == 0)

sNum.push(SuffixExp[i].nNum);

else

{

double y = sNum.top();

sNum.pop();

double x = sNum.top();

sNum.pop();

switch (SuffixExp[i].cOp)

{

case ‘+‘:

x += y;

break;

case ‘-‘:

x -= y;

break;

case ‘*‘:

x *= y;

break;

case ‘/‘:

x /= y;

break;

}

sNum.push(x);

}

}

printf("%.2f\n", sNum.top()); //輸出結果

return 0;

}

}

簡單計算器的編程【C++】