0
Hello I need a little explanation. Im a beginner
x = float(input()) while x <= 200: if x%2 == 0: print(str(x) + " is even") else: print(str(x) + " is odd") x += 0.1 When I run this following code and I type 0 as the input, why does not just increase by 0.1 and randomly. For example one of the outputted lines was like 0.39999999... Please explain clear and concise id appreciate it this is python
3 ответов
+ 6
visph gave you the answer.
To fix it, you can round x to the nearest single decimal place by changing
x += 0.1
to
x = round(x + 0.1, 1)
+ 5
as in many languages, python internally store float as binary floating point with a fixed prevision... so some values expressed as decimal are a few innacurate ^^
more detailled explanation here:
https://www.geeksforgeeks.org/floating-point-error-in-python/
+ 1
You need to learn while and for loop first and your code only excutes ones