不能对双打使用模数吗?
我有一个 C++ 程序(使用 g++ 编译)。我试图将两个双精度数作为操作数应用于模函数,但出现以下错误:
错误:“double”和“double”类型的操作数对二进制“operator%”无效
这是代码:
int main() {
double x = 6.3;
double y = 2;
double z = x % y;
}
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:
error: invalid operands of types 'double' and 'double' to binary 'operator%'
Here's the code:
int main() {
double x = 6.3;
double y = 2;
double z = x % y;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
%
运算符用于整数。您正在寻找fmod()
函数。The
%
operator is for integers. You're looking for thefmod()
function.fmod(x, y)
是您使用的函数。fmod(x, y)
is the function you use.您可以实现自己的模函数来为您做到这一点:
然后您可以简单地使用
dmod(6.3, 2)
来获得余数,0.3
。You can implement your own modulus function to do that for you:
Then you can simply use
dmod(6.3, 2)
to get the remainder,0.3
.使用
中的fmod()
。如果您不想包含 C 头文件:Use
fmod()
from<cmath>
. If you do not want to include the C header file:这是一个同时适用于正数和负数的函数:
如果 x 为负数或正数,它将始终返回正数。
请注意,如果
y
为负数,则返回值将为负数。如果您需要一个在任何情况下都返回正值的函数,那么需要使用y
上的std::fabs()
,即:Here is a function that also works with both positive and negative numbers:
It will always return a positive number if
x
is negative or positive.Note that if
y
is negative, the returned value will be negative. If you need a function that will return a positive in any case, then one need to usestd::fabs()
ony
, i.e.: