计算以字符串形式输入的等式

时间:2014-10-01 01:56:19

标签: string math python-3.x equation

我必须编写多个函数来解决数学难题。其中一个函数在等式的一侧并计算答案。等式输入为字符串。我已经创建了变量以便继续对数字进行计数,使得22为22而不是2,2等。当运行此函数时,它会打印-4。参数Blackout设置为22-11 * 4。我对这个问题是什么以及我得到-4的原因感到困惑。也许这个等式被倒退并跳过一些数字?

def compute(Blackout):
numberBuild = ""
operator = ""
prev = 0
total = 0
for i in range (0 , len(Blackout)):
    current = Blackout[i]

    if current.isdigit():
        numberBuild = current
    else:
        operator = current

    if prev == 0 and operator != "":
        prev = numberBuild
        numberBuild = ""

    if prev != 0 and operator != "":
        if operator == "+":
            total = total + int(prev)
        elif operator == "-":
            total = total - int(prev)
        elif operator == "x":
            total = total * int(prev)
        elif operator == "/":
            total = total / int(prev)
    prev = 0
    i + 1

print(total)

0 个答案:

没有答案