C++ 不能在双打上使用模数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9138790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't use modulus on doubles?
提问by Bhaxy
I have a program in C++ (compiled using g++). I'm trying to apply two doubles as operands to the modulus function, but I get the following error:
我有一个 C++ 程序(使用 g++ 编译)。我正在尝试将两个双精度数作为操作数应用于模数函数,但出现以下错误:
error: invalid operands of types 'double' and 'double' to binary 'operator%'
错误:“double”和“double”类型的无效操作数转换为二进制“operator%”
Here's the code:
这是代码:
int main() {
double x = 6.3;
double y = 2;
double z = x % y;
}
回答by Mysticial
The %
operator is for integers. You're looking for the fmod()
function.
该%
运算符用于整数。您正在寻找fmod()
功能。
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}
回答by MSN
fmod(x, y)
is the function you use.
fmod(x, y)
是你使用的函数。
回答by Sceptical Jule
Use fmod()
from <cmath>
. If you do not want to include the C header file:
fmod()
从使用<cmath>
。如果不想包含 C 头文件:
template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
return !mod ? x : x - mod * static_cast<long long>(x / mod);
}
//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);
回答by Mystical
You can implement your own modulus functionto do that for you:
您可以实现自己的模数函数来为您做到这一点:
double dmod(double x, double y) {
return x - (int)(x/y) * y;
}
Then you can simply use dmod(6.3, 2)
to get the remainder, 0.3
.
然后您可以简单地使用dmod(6.3, 2)
来获取余数,0.3
。