Home > Enterprise >  Calculate how many of each groups a number is consisted issue?
Calculate how many of each groups a number is consisted issue?

Time:11-07

I found that if you type 0.30 in the below, it will result that is consisted only of the 0.20. The expected result is to calculate that 0.30 is consisted of 1 time a 0.20 and 1 time a 0.10. Other numbers seem to work correctly.

x = float(input('Type a number ')) #Type 0.30
print(x // 1, "1")
x = x % 1
print(x // 0.50, "0.50")
x = x % 0.50
print(x // 0.20, "0.20")
x = x % 0.20
print(x // 0.10, "0.10")

Results

The actual result is:
0.0 1
0.0 0.50
1.0 0.20
0.0 0.10

The expected is:
0.0 1
0.0 0.50
1.0 0.20
1.0 0.10

CodePudding user response:

I think it gets clear when you also print x in between:

x = float(input('Type a number ')) #Type 0.30
print(x // 1, "1")
x = x % 1
print(x)
print(x // 0.50, "0.50")
x = x % 0.50
print(x)
print(x // 0.20, "0.20")
x = x % 0.20
print(x)
print(x // 0.10, "0.10")

Output:

0.0 1
0.3
0.0 0.50
0.3
1.0 0.20
0.09999999999999998
0.0 0.10

Knowing that it makes sense when you see how float values are stored in python: https://docs.python.org/3/tutorial/floatingpoint.html

  • Related