Search code examples
pythonfloating-point

Why different output of numbers?


In this program, when I input 3 numbers 13, 179, 0 I get 2 different outputs from 2 equivalent programs, first - 202 26, second - 202 27. Why?

P = int(input())
X = int(input())
Y = int(input())

# first program outputs 202 26 (not correct)
summ = int((X * 100 + Y) * ((100 + P) / 100))
rub = summ // 100
kop = summ % 100
print(rub, kop)

# second program outputs 202 27 (correct)
money_before = 100 * X + Y
money_after = int(money_before * (100 + P) / 100)
print(money_after // 100, money_after % 100)

Input 13, 179 and 0 and get 202 26 from first program and 202 27 from second. The second is correct.


Solution

  • The issue relates to order of evaluation.

    Your original code:

    summ = int((X * 100 + Y) * ((100 + P) / 100))
    

    ...will be equivalent to your second code fragment if you remove parentheses as follows:

    summ = int((X * 100 + Y) * (100 + P) / 100)