Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use modulus on doubles?

Tags:

c++

modulo

People also ask

Can you do modulus on doubles?

If either or both operands of the mod operator have type double, then evaluating it produces the remainder. This kind of mod operator does not exist in C or C++ where the mod operator only works with int operands. The evaluated result is a double value.

Can you use modulus with floats?

Yes, %(modulo) operator isn't work with floats and double.. if you want to do the modulo operation on large number you can check long long int(64bits) might this help you.

Can modulus operator be used with double in C?

The modulus operator cannot be used with a long double.


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

}

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


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

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.