2016-04-20 16 views
1
userchoice = raw_input('What do you want to calculate?\nmass, acceleration or force') 

def calculator(): 
    if userchoice == 'mass': 
     acceleration = int(raw_input('What will be the acceleration?')) 
     force = int(raw_input('And what it will be the force?')) 
     return force/acceleration 

    elif userchoice == 'force': 
     acceleration = int(raw_input('What will be the acceleration?')) 
     mass = int(raw_input('And what it will be the mass?')) 
     return mass * acceleration 

    elif userchoice == 'acceleration': 
     force = int(raw_input('And what it will be the force?')) 
     mass = int(raw_input('And what it will be the mass?')) 
     return force/mass 

    else: 
     return "You didn't choose any of the available options" 


print calculator() 

在我運行任何流程之後,我得到0作爲結果而不是操作。 採取以下流程:用戶選擇質量,他輸入加速度20和2的力量。結果應該是10,但我得到0.簡單的計算器函數返回0而不是操作(例如質量*加速度)

回答

0

除法輸出默認鑄造爲int。使用float()方法如下:

userchoice = raw_input('What do you want to calculate?\nmass, acceleration or force') 

def calculator(): 
    if userchoice == 'mass': 
     acceleration = int(raw_input('What will be the acceleration?')) 
     force = int(raw_input('And what it will be the force?')) 
     return float(force)/float(acceleration) 

    elif userchoice == 'force': 
     acceleration = int(raw_input('What will be the acceleration?')) 
     mass = int(raw_input('And what it will be the mass?')) 
     return float(mass) * float(acceleration) 

    elif userchoice == 'acceleration': 
     force = int(raw_input('And what it will be the force?')) 
     mass = int(raw_input('And what it will be the mass?')) 
     return float(force)/float(mass) 

    else: 
     return "You didn't choose any of the available options" 


print calculator() 

,它會正常工作:

>>> ================================ RESTART ================================ 
>>> 
>>> 
What do you want to calculate? 
mass, acceleration or forcemass 
What will be the acceleration?3 
And what it will be the force?5 
1.66666666667 
+0

現在使用浮動工作正常。謝謝! – afodor88

0

我發現這個問題......我想,當我給加速度20和力2,我應該得到10,因爲手術將加速/力量,但它實際上是力量/加速度...