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?
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?
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)
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
.