#include <stdio.h>
int main() {
int x = 9;
int y = 2;
int z = x - (x / y) * y;
printf("%d", z);
return 0;
}
Why does this code print the value of x % y
?
From a strictly mathematical standpoint, (x/y)*y
is the same as x
, so one might expect 0 to be printed if looked at in this way.
The reason has to due with how the /
operator works with particular types.
The division operation x/y
is performed as integer division because both operands are integer types. So the resulting value has the fractional portion of the division truncated.
Multiplying this result by y
will therefore not necessarily be the same as x
due to the truncation of the result value. The difference between this result and x
is x%y
.
From section 6.5.5 of the C standard :
6 When integers are divided, the result of the
/
operator is the algebraic quotient with any fractional part discarded. If the quotienta/b
is representable, the expression(a/b)*b + a%b
shall equala
; otherwise, the behavior of botha/b
anda%b
is undefined.
So the standard explicitly states that this equality holds.
If either operand of the division was a floating point type, then x-(x/y)*y
would always be 0 or a value very close to 0 due to the inexact nature of floating point operations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.