0

I'm just working on a personal project with calculating time/speed/distance. I've encountered a problem with my program though, when I input say 36 for kms to cover and 100 km/h as speed, the program which should give me back a result such as 21.6 minutes but instead it gives me 0 minutes.

However when I input 36.0 and 100, the program works perfectly to what I want. Why is it when I've inputted a decimal for my kms to cover it works fine yet when an integer is input it will not calculate properly.

Interested to see what the problem could be, is it the order of my code? Perhaps, making the variable a float or some such thing could be the fix? Not sure what the issue is since it occurs on such a specific thing such as ensuring the number is a decimal. Still learning Python as you can probably tell from my code.

Thanks in advance for your assistance.

Code is as follows;

print('Welcome to my calculator')

d = float(input('How many kms do you want to cover? '))
s = float(input('How fast will you be travelling (km/h)? '))
t = d/s
  if t < 1:
     t = t * 60
     print('You will reach your destination in ') + str(t) + (' minutes.')
  else:
     print('You will reach your destination in ') + str(t) + (' hours.')
Just Ice
  • 179
  • 1
  • 1
  • 11
Muzzy
  • 11
  • 3
  • Thank you so much for the explanation and help, apologies for the duplicate question, I guess I didn't know what to search for! – Muzzy Jul 27 '16 at 10:08

2 Answers2

0

I guess your problem is integer division. You could fix it by changing t = d/s to t = float(d)/s.

>>> 2/5
0
>>> float(2)/5
0.4

This issue has been solved in Python 3.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
0

You are making an integer division. Try converting d or s to a float.

t = float(d)/s

And this will return the expected output. You could also have done:

t = (d * 1.0)/s

to avoid TypeError if d is, for instance, a complex number.


By default, in Python2, when you use / between two integers, it performs an integer division. If one of the two numbers is a float, it performs a decimal division.

Also note that it is recommended that you put the user inputs in a try/except block.

Graham
  • 7,431
  • 18
  • 59
  • 84
AdrienW
  • 3,092
  • 6
  • 29
  • 59