i cant understand the second line of the below code:
for (int i = n - 1; i >= 0; i--)
{
ans += (a[i] - ans * r > 0);
printf("%d\n", ans);
}
i cant understand the second line of the below code:
for (int i = n - 1; i >= 0; i--)
{
ans += (a[i] - ans * r > 0);
printf("%d\n", ans);
}
When in doubt, simplify.
Due to operator precedence, the line
ans += (a[i] - ans * r > 0);
is equivalent to:
ans += ((a[i] - ans * r) > 0);
To make it more readable, use:
bool temp1 = ((a[i] - ans * r) > 0);
ans += temp1;
When used in a term such as ans += temp1
, a bool
gets converted/promoted to 1
if the value is true
and to 0
if the value is false
.
A further simplification would be:
bool temp1 = ((a[i] - ans * r) > 0);
int temp2 = (temp1? 1 : 0);
ans += temp2;
In the end, ans
gets incremented by 1
if (a[i] - ans * r) > 0
. Otherwise, its value remains unchanged.