計算器的算法實現


重點有:

  1. 將輸入的表達式轉化為逆波蘭表達式
  2. 操作符進出棧處理
  3. 檢測小數或多位數的情況
  4. 本算法實現采用從左向右計算

想想學數據結構的時候還是大一下學期,轉眼·····歲月是把豬食料。說點重點,計算器用到的知識點主要就是棧的應用,操作符進、出棧的處理,以及碰到括號的時候處理的方式。如果你C語言用的比較順手,建議用C語言處理,能對棧的知識加強理解和應用。

本算法實現時,先將乘除運算處理,之后剩余的加減從左向右一次計算。但還是希望你看下關於波蘭表達式的知識。

Python代碼如下:

import re
you_put=input("輸入你要計算的算式:\n")
num_stack=[]#用於對數字的存儲
str_stack=[]#用於對操作符的存儲
i=0
def cal(x,y,st):
    res=0
    x=float(x)
    y=float(y)
    if st is '+':
        res=x+y
    elif st is '-':
        res=x-y
    elif st is '*':
        res=x*y
    else:
        res=x/y
    return res
def process(num_stack,str_stack):
    st = str_stack.pop()
    num_stack[len(num_stack) - 2] = cal(num_stack[len(num_stack) - 2],\
    num_stack[len(num_stack) - 1], st)
    num_stack.pop()
while i<len(you_put):
    #判斷掃描到的s[i]是操作數
    if you_put[i].isdigit():
        #當數值為多位數時,采用正則匹配
        num=(re.search(r'(\d+)',you_put[i:])).group()
        length=len(num)
        #先將'*'或者'/'計算出結果。例如:1-2*3-->1-6
        if len(num_stack)>0 and str_stack[len(str_stack)-1] in ['*','/']:
            num=cal(num_stack[len(num_stack)-1],num,str_stack[len(str_stack)-1])
            num_stack[len(num_stack)-1]=num
            str_stack.pop()
        else:
            num_stack.append(num)
        i+=length
        continue
    if you_put[i] is '(':
        #掃描到的s[i]是開括號'(',將s[i]壓棧;
        str_stack.append(you_put[i])
        i+=1
        continue
    if you_put[i] in ['+','-','*','/','(']:
        #棧頂為'(' 或 掃描到的操作符優先級比棧頂操作符高
        if you_put[i] in ['*','/','(']:
            str_stack.append(you_put[i])
            i+=1
            continue
        else:
            if len(str_stack)==0:
                str_stack.append(you_put[i])
                i += 1
                continue
            elif str_stack[len(str_stack)-1] in ['*','/']:
                process(num_stack,str_stack)
                str_stack.append(you_put[i])
                i+=1
                continue
            else:
                str_stack.append(you_put[i])
                i+=1
                continue
    if you_put[i] is ')':
        while str_stack[len(str_stack)-1] is not '(':
            process(num_stack, str_stack)
        str_stack.pop()    #彈出'('
        i+=1
while len(num_stack)>1:
    #因為之前已經將'*','/'計算過,所以現在僅剩'+','-'
    temp=0
    st = str_stack.pop(temp)
    num_stack[temp+1] = cal(num_stack[temp],num_stack[temp+1], st)
    num_stack.pop(temp)
print(num_stack[0])

運行結果截圖如下:

測試較少,如有錯誤或不妥之處,請多指出。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM