0
Why doesn't this code display correct?
Code : i = 0 while i<=10: print(i) i += 0.1 It displays other numbers than 0.1 0.2 0.3 0.4 and ... How can I fix this?
5 odpowiedzi
+ 2
Format the output to show only 1 digit following the decimal point
i = 0.0
while i <= 10.0:
print( f"{i:.1f}" ) # .1 means only 1 digit following the decimal point
i += 0.1
+ 2
The decimal point makes conversion to `int` failed. Looks like it is necessary to first convert the string into a `float`, then convert the `float` value into `int`.
n = 12.345 # float
sn = f"{n:.1f}" # string
print( sn )
print( int( float( sn ) ) ) # to float first, then to int.
+ 1
What is your excepted output?
+ 1
Ipang Thanks alot!
0
Ipang sorry for asking again, how can i do i = f"{i:.1f}" ?
it becomes an str value and when i put i = int(i) it shows another error