gpt4 book ai didi

c - 为什么 (x-(x/y)*y) 的计算结果与 x%y 相同?

转载 作者:行者123 更新时间:2023-11-30 21:15:18 26 4
gpt4 key购买 nike

#include <stdio.h>

int main() {
int x = 9;
int y = 2;
int z = x - (x / y) * y;
printf("%d", z);
return 0;
}

为什么这段代码会打印x % y的值?

从严格的数学角度来看,(x/y)*yx 相同,因此如果这样看,人们可能会期望打印 0 .

最佳答案

原因在于 /运算符适用于特定类型。

除法运算x/y执行为整数除法,因为两个操作数都是整数类型。因此结果值的除法小数部分被截断。

将此结果乘以 y因此不一定与 x 相同由于结果值被截断。这个结果和 x 的区别是 x%y .

摘自 C standard 的第 6.5.5 节:

6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined.

因此标准明确指出这种等式成立。

如果除法的任一操作数是浮点类型,则 x-(x/y)*y由于浮点运算的不精确性质,它始终为 0 或非常接近 0 的值。

关于c - 为什么 (x-(x/y)*y) 的计算结果与 x%y 相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41875926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com