我的任務是以字符串的形式接受數學運算並以整數形式返回答案。操作順序也被忽略,數學運算必須從左到右解決。爲什麼我的'while'循環沒有返回值?
我的代碼可能可能更短/更簡單,但這是我想出的。我的策略是遍歷字符串中的每個字符,直到我碰到一個運算符(+, - ,x,/)。然後運算符之前的數字串變成一個整數。操作員被存儲爲變量c
,以便可以使用當前編號和遇到的下一個編號(c = 1表示加法等)完成操作。
當我運行程序時,它應該打印變量total
,但不打印任何東西。 return
語句是否退出當前的if
語句或退出while
循環?問題是別的嗎?
def compute(e):
a=0 #starting index used to check specific characters in string
b=0 #to keep track of index after last operator
l=len(e) #length of e to use for while loop
st=""
total=0 #result of all previous calculations
count=0 #keeps track of number of operators passed
c=0 #Used to keep track of what operator was last passed
#c=1 is addition
#c=2 is subtraction
#c=3 is multiplication
#c=4 is division
while l>0:
if e[a].isdigit():
return
elif e[a]=="+" or e[a]=="-" or e[a]=="x" or e[a]=="/": #When an operator is detected in string
st=e[b:a] #To combine all numbers between two operators into one string
count=count+1 #to keep track of number of operators passed
b=a+1 #now b is the index after the last operator
if count==1: #This is the first operator encountered in string
total=int(st) #The string is stored as total because this is the first integer stored
else:
num=int(st) #The string of numbers is stored as num instead of total
if count==1: #This means this is the first operator and there should not be an operation done yet
return
elif c==1:
total=total+num
elif c==2:
total=total-num
elif c==3:
total=total*num
elif c==4:
total=total/num
if e[a]=="+":
c=1
elif e[a]=="-":
c=2
elif e[a]=="x":
c=3
elif e[a]=="/":
c=4
else:
return None
a=a+1
l=l-1
print(total)
compute("22-11x4")
input("Wait")
return語句退出整個功能,它打破了任何和所有的循環。 – BrenBarn 2014-09-30 04:11:05
@BrenBarn所以可以放置在剛剛脫離當前if語句的返回語句的位置? – krzy122 2014-09-30 04:14:40
使用** continue **語句在while循環中跳過其餘的執行而不是返回語句 – 2014-09-30 04:18:46