Why doesn't this code display correct? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
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?

5th Feb 2021, 4:48 PM
Sadra Shakouri
Sadra Shakouri - avatar
5 Respostas
+ 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
5th Feb 2021, 5:02 PM
Ipang
+ 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.
5th Feb 2021, 5:23 PM
Ipang
+ 1
What is your excepted output?
5th Feb 2021, 5:00 PM
Atul [Inactive]
+ 1
Ipang Thanks alot!
5th Feb 2021, 5:05 PM
Sadra Shakouri
Sadra Shakouri - avatar
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
5th Feb 2021, 5:12 PM
Sadra Shakouri
Sadra Shakouri - avatar