Reputation: 5574
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;
}
Upvotes: 248
Views: 289094
Reputation: 440
Here is a function that also works with both positive and negative numbers:
#include <cmath>
inline double nmod(double x, double y) {
return std::fmod(std::fmod(x, y) + y, y);
}
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 use std::fabs()
on y
, i.e.:
inline double nmod2(double x, double y) {
return std::fmod(std::fmod(x, y) + std::fabs(y), y);
}
Upvotes: 1
Reputation: 471289
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);
}
Upvotes: 343
Reputation: 2783
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
.
Upvotes: 10
Reputation: 917
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);
Upvotes: 6