为什么 C 中同时存在 % 和 fmod()

Why do both % and fmod() exist in C

我今天在我的 CS class 中参加了一个小测验,并且有一个关于模运算符的问题是错误的,因为我不知道 C 中 % 的可用性,我一直在使用 fmod().为什么两者都存在?是一个 better/faster 还是它们只处理不同的数据类型?

因为%是整数运算符,而fmod代表floatmod,用于浮点数。

% 只是整数模

fmod 是浮点模,可以按照 MSDN 中的描述使用。 https://msdn.microsoft.com/en-us/library/20dckbeh.aspx

modulo division 在 C 中使用 % 运算符仅适用于整数操作数和 returns 除法的整数余数。 函数 fmod 接受 double 作为参数,这意味着它接受 non-integer 个值和 returns 除法的余数。

关于 fmod 的附加说明:double 操作数的余数如何计算?感谢@chux 展示 documentation fmod 如何计算浮点除法的余数。

The floating-point remainder of the division operation x/y calculated by this function is exactly the value x - n*y, where n is x/y with its fractional part truncated.

The returned value has the same sign as x and is less or equal to y in magnitude.

另一方面,在最初设计模除法二元运算符(%)时,语言设计者确定它只支持'integer'类型的操作数,因为从技术上讲, 'remainder'在数学中只适用于整数除法。

Why do both exist?

因为他们可能计算出不同的结果,即使是相同的值。这些差异可能会出现负值。本质上 fmod()% 不同的数学函数。

fmod(x,y),从 C89 开始,结果为 "the result has the same sign as x and magnitude less than the magnitude of y"。

i%j 并没有被如此单一地定义。参见 Remainder calculation for the modulo operation. This allow code to use existing variant processors effectively. The div() function was created to address this variability. Ref

通过 C99,他们对相同的值进行相同的计算。未来 C 可以允许 123.4 % 56.7