Python中的加法出错

2024-04-25 01:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的初学者,正在编写一个基本的计算器

while True:
    print("PyCalc")
    print()
    print()
    init=input("Press 1 for Basic arithmetic")
    if init=="1":
        input1=input("Basic Arithmetic...Only +,-,*,/ accepted...")
        input2=re.findall(r'\d+|\+|\-|\*|\/',input1 )
        ans =basiccalc(input2)
        print(ans )

基本方法:

def basiccalc(givenlist):
    ans=int(givenlist[0])
    for pt in givenlist:
        if str(pt).isdigit():
            continue
        elif pt=='+':
            pos=givenlist.index(pt)
            ans=ans+int(givenlist[pos+1])

return ans

当我运行程序时…添加2个数字是正确的。你知道吗

  PyCalc


  Press 1 for Basic arithmetic1
  Basic Arithmetic...Only +,-,*,/ accepted...2+3
  5

但当我输入两个以上的数字…它给了我一个错误的答案

PyCalc


Press 1 for Basic arithmetic1
Basic Arithmetic...Only +,-,*,/ accepted...2+4+5+6
14

为什么我会得到这样的答案?你知道吗


Tags: ptonlyforinputifbasicinitarithmetic
1条回答
网友
1楼 · 发布于 2024-04-25 01:29:33

第一个问题您必须使用原始输入函数而不是输入,因为输入已经计算了对输入的算术运算。你知道吗

第二个问题是basiccalc函数中超过2个数字最后一个没有计算,请尝试:

import re

def sum(a,b):
    return a+b


def basiccalc(givenlist):
    ans=0
    op=sum
    for pt in givenlist:
        if str(pt).isdigit():
            ans = op(ans,int(pt))
            last = int(pt)
        elif pt=='+':
            op=sum
    return ans            

input1=raw_input("Basic Arithmetic...Only +,-,*,/ accepted...")
input2 = re.findall( r'\d+|\+|\-|\*|\/', input1 )
ans = basiccalc(input2)
print(ans)

有关解析的更多信息,请参阅Dragon Book代码示例: https://github.com/lu1s/dragon-book-source-code/blob/master/parser/Parser.java

相关问题 更多 >