0

This program is written to find area of a rectangle.

l = float(input("Lenght of rectangle:"))
b = float(input("Breadht of rectangle:"))
area = l*b
print ("Area of square = l*b")
print ("               =",l,"*",b)
print ("               =",area)

The input length is 12.4 and the input breadth is 13 So the answer must be 161.2 however the answer coming is 161.20000000000002 What's going wrong?

Mistu4u
  • 5,132
  • 15
  • 53
  • 91
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Ian Cook Jan 31 '21 at 14:30

2 Answers2

0

Check out https://medium.com/code-85/how-to-stop-floating-point-arithmetic-errors-in-python-a98d3a63ccc8.

"This happens because decimal values are actually stored as a formula and do not have an exact representation."

formicaman
  • 1,317
  • 3
  • 16
  • 32
0

Use the following program instead of the above one

l = float(input("Lenght of rectangle:"))
b = float(input("Breadht of rectangle:"))
area = (l*b)
a_float = "{:.2f}".format(area)
print ("Area of square = l*b")
print ("               =",l,"*",b)
print ("               =",area)

Here, we have format the program so that we only get two digits after the decimal. in this way the outcome will be similar to what we exactly wanted.

For more information, visit https://www.kite.com/python/answers/how-to-print-a-float-with-two-decimal-places-in-python#:~:text=Use%20str.,number%20with%20two%20decimal%20places.

reference:- www.kite.com