Can't use modulus on doubles?

C++Modulo

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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

}

Solution 2 - C++

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

Solution 3 - C++

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.

Solution 4 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBhaxyView Question on Stackoverflow
Solution 1 - C++MysticialView Answer on Stackoverflow
Solution 2 - C++MSNView Answer on Stackoverflow
Solution 3 - C++MysticalView Answer on Stackoverflow
Solution 4 - C++Sceptical JuleView Answer on Stackoverflow