In C++, remainder and modulo operations are represented using different operators.
The remainder operation is represented by the percent sign ( %
) operator
For example, to calculate the remainder when dividing 10 by 3, you can use the following code:
int result = 10 % 3
;
Here, the % operator calculates the remainder of dividing 10 by 3 and assigns the result to the variable result. In this example, the value of result will be 1.
The modulo operation is expressed using the modulo operator ( std::fmod
). The modulo operator is a function in the C++ standard library and needs to include a header file. For example, to calculate the remainder of -10 divided by 3, you can use the following code:
#include <cmath>
double result = std::fmod(-10, 3);
Here, std::fmod
the function calculates the remainder when dividing -10 by 3 and assigns the result to the variable result. In this example, the value of result will be -1.0.
It should be noted that the remainder operation and the modulo operation are equivalent for operands of integer type, but different for operands of floating point type. When dealing with floating-point numbers, the modulo operation (std::fmod) should be used instead of the modulo operation (%) .
Summary:
In general, whether it is modulo or remainder, the following framework can be used
//fmod函数必须要包含的头文件
#include <cmath>
//C++标准库中的取余和取模函数
std::fmod(x1,x2);