-6

when I perform 12*20/100, I get 2 as the output

but when I perform 12*(20/100), I get 0 as the output

So does anyone know why the brackets affect the output?

Aditi Rawat
  • 784
  • 1
  • 12
  • 15

2 Answers2

1

It is because (20/100) as integer division evaluates to 0. use (20.0/100) to get 0.2. Without parentheses you have 240 / 100 = 2 (as integer)

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

In mathematics, parentheses don't matter for your expression.

But C++ computation (especially integer arithmetic) isn't mathematics. You already understand that, as you accept 12*20/100 being 2 instead of 2.4.

Setting parentheses defines what to compute first (as in mathematics), so 12*(20/100) first computes 20/100, giving 0, and then 12*0, giving 0.

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7
  • I disagree, not all calculation "in mathematics" happens in ℝ or whatever domain you had in mind. This kind of integer division goes all the way back to Euclid around 300BCE, it's certainly not just some unmathematical C++ quirk. – harold Dec 30 '17 at 00:07