Can't use modulus on doubles?

你说的曾经没有我的故事 提交于 2019-11-26 02:33:21

问题


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;
}

回答1:


The % operator is for integers. You're looking for the fmod() function.

#include <cmath>

int main()
{
    double x = 6.3;
    double y = 2.0;
    double z = std::fmod(x,y);

}



回答2:


fmod(x, y) is the function you use.




回答3:


Use fmod() from <cmath>. If you do not want to include the C header file:

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);



回答4:


You can implement your own modulus function to 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.



来源:https://stackoverflow.com/questions/9138790/cant-use-modulus-on-doubles

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!