C 簡單計算器實現(四則運算加括號)

2021-07-25 07:14:13 字數 1562 閱讀 2979

先說一下實現思路,使用兩個棧,乙個存放數字,乙個存放運算子。這樣比較運算子和取出運算的數字都非常方便。再者,在壓入棧的過程中,把要壓入的運算子和前乙個運算子進行比較,如果優先順序小於或者等於,就要將前乙個運算子進行計算。

ps:支援帶括號帶負數四則運算。

#include 

#include

#include

using

namespace

std;

stack

num_stk;

stack

oper_stk;

string experssion;

double result;

int number_flag;

void pop_caculate();

int cal_priority(char c);

string::size_type get_number_size(string &expr,string::size_type currentpos);

bool is_number(char c);

void caculate(string expr);

int main()}/*

* get number length from currentpos of string expr

*/string::size_type get_number_size(string &expr,string::size_type currentpos) /*

* char c is number?

*/bool is_number(char c)

return

true;}/*

* the main caculate method

*/void caculate(string expr)

size = get_number_size(expr,i);

num_stk.push(num);

i += size;

cout

<< "num:"

<< num << endl;

number_flag = 1;

} else else

if (expr[i] == '(') else

if (expr[i] == ')')

oper_stk.pop();

} else

if (cal_priority(expr[i]) <= cal_priority(oper_stk.top())) else

++i;}}

while (!oper_stk.empty())

result = num_stk.top();

cout

<< result << endl;}/*

* pop and caculate the two stack to caculate

*/void pop_caculate()

/* * caculate operator priority

*/int cal_priority(char c)

棧實現計算器(簡單四則運算)

主要是通過定義乙個數棧和乙個符號棧,並根據給出的計算式進行拆分,迴圈判斷是數字還是符號,考慮數字的連續性和符號計算的優先順序,具體實現如下 package com.pangzi.stucture public class calculator else else elseelse 讓index 1,...

python 計算器 四則運算

學習來自 感謝!思路 考慮的四則運算符號 獲取表示式字串 表示式切分 請注意區分 減號 與負號 先出初切 formula list i for i in re.split d d formula if i 然後再判定 if re.search final formula 1 其他正常切分就行 ite...

四則運算計算器

今天做個帶視窗的c 四則運算計算器 輸入中綴表示式 自然表示式 可以用list來放 先把它變成字尾表示式 逆波蘭表示式 用乙個棧放運算子,另乙個棧放字尾表示式 運算子優先順序 1 2 3 4 從左到右遍歷中綴表示式 計算字尾表示式 從左到右掃瞄字尾表示式,如果是數字,放入數字棧。如果是符號,從數字棧...