python要处理除法向0取整
做法:有两个数a,b,如果a//b是正数的话,则不用处理。反之,如果a不能被b整除,那么将结果+1就是向0取整,比如 v = 5//-3 = -2, v+=1就是想要的结果
代码
def evaluate():
b, a, c = num.pop(), num.pop(), op.pop()
x = 0
if c == '+': x = a+b
elif c == '-': x = a-b
elif c == '/':
x = a // b
if x < 0 and a % b: x += 1
else: x = a*b
num.append(x)
pr = {'+':1, '-':1, '*':2, '/': 2}
s = str(input())
num, op = list(), list()
i = 0
while i < len(s):
c = s[i]
if c.isdigit():
v = ''
while i < len(s) and s[i].isdigit():
v += s[i]
i += 1
i -= 1
num.append(int(v))
elif c == '(':
op.append(c)
elif c == ')':
while op[-1] != '(':
evaluate()
op.pop()
else:
while len(op) and op[-1] != '(' and pr[op[-1]] >= pr[c]:
evaluate()
op.append(c)
i+=1
while len(op): evaluate()
print(num.pop())