Why does modulus division (%) only work with integers?(为什么模数除法 (%) 仅适用于整数?)
问题描述
我最近遇到了一个问题 可以使用模数除法轻松解决,但输入是浮点数:
I recently ran into an issue that could easily be solved using modulus division, but the input was a float:
给定一个周期函数(例如sin)和一个只能在周期范围内计算它的计算机函数(例如[-π, π]),制作一个可以处理任何输入的函数.
Given a periodic function (e.g.
sin) and a computer function that can only compute it within the period range (e.g. [-π, π]), make a function that can handle any input.
明显"的解决方案类似于:
The "obvious" solution is something like:
#include <cmath>
float sin(float x){
return limited_sin((x + M_PI) % (2 *M_PI) - M_PI);
}
为什么这不起作用?我收到此错误:
Why doesn't this work? I get this error:
error: invalid operands of types double and double to binary operator %
有趣的是,它确实适用于 Python:
Interestingly, it does work in Python:
def sin(x):
return limited_sin((x + math.pi) % (2 * math.pi) - math.pi)
推荐答案
因为余数"的正常数学概念仅适用于整数除法.即生成整数商所需的除法.
Because the normal mathematical notion of "remainder" is only applicable to integer division. i.e. division that is required to generate integer quotient.
为了将余数"的概念扩展到实数,您必须引入一种新的混合"操作,该操作将为实数操作数生成整数商.核心 C 语言不支持这种操作,但它作为标准库提供 fmod 函数,以及 remainder 函数C99.(注意,这些函数并不相同,有一些特殊性.特别是,它们不遵循整数除法的舍入规则.)
In order to extend the concept of "remainder" to real numbers you have to introduce a new kind of "hybrid" operation that would generate integer quotient for real operands. Core C language does not support such operation, but it is provided as a standard library fmod function, as well as remainder function in C99. (Note that these functions are not the same and have some peculiarities. In particular, they do not follow the rounding rules of integer division.)
这篇关于为什么模数除法 (%) 仅适用于整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么模数除法 (%) 仅适用于整数?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
