gpt4 book ai didi

我可以依赖 C 中的 %(模)运算符来获取负数吗?

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:01 40 4
gpt4 key购买 nike

使用海湾合作委员会:

printf("%i \n", -1 % (int)4);
printf("%u \n", -1 % (unsigned int)4);

输出:

-1
3

我可以跨平台依赖这种行为吗?我是否应该显式定义 MODREM 宏以确保它没有被更改?

最佳答案

从 C99 开始,% 的结果需要向 0 舍入,正如 Chris Dodd 所引述的那样。

在 C99 标准之前,% 运算符对负数的行为是实现定义的

When integers are divided and the division is inexact, if both operands are positive the result of the / operator is the largest integer less than the algebraic quotient and the result of the % operator is positive. If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

Does either ANSI C or ISO C specify what -5 % 10 should be?

因此如果您的目标是 C99 或更新版本,结果是,否则您不能依赖它。

如果您需要一致的结果以及对更旧的 C 标准的可移植性,您可以使用 div or ldiv , 无需定义自己的 MODREM

C99 rationale regarding div, ldiv, and lldiv functions :

Because C89 had implementation-defined semantics for division of signed integers when negative operands were involved, div and ldiv, and lldiv in C99, were invented to provide well-specified semantics for signed integer division and remainder operations.

关于我可以依赖 C 中的 %(模)运算符来获取负数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29179337/

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