Convert negative angle to positive: Involves invalid operand use
Solution 1
Okay perhaps I'm a little slow, but I'm not sure why you're using a 3600000.0 constant.
If you're just trying to convert a negative angle to it's positive value, you can just add 360.0 until you get a positive number.
double to_positive_angle(double angle)
{
angle = fmod(angle, 360);
while(angle < 0) { //pretty sure this comparison is valid for doubles and floats
angle += 360.0;
}
return angle;
}
Solution 2
This version works for all possible inputs, not just ones greater than 3600000, and solves the %
issue you were experiencing.
double to_positive_angle(double angle)
{
angle = fmod(angle, 360);
if (angle < 0) angle += 360;
return angle;
}
Solution 3
You can't use the modulo operator on floating-point types. You should use fmod
for this.
return fmod( 3600000.0 + angle, 360.0 );
Be a little wary of rounding and precision errors you might introduce with the above operation.
sazr
Updated on June 14, 2022Comments
-
sazr almost 2 years
I am attempting to convert a negative angle (in degrees) to positive. But I am getting a compile error saying:
test.cpp invalid operands of types 'double' and 'int' to binary 'operator%'
test.cpp invalid operands of types 'float' and 'int' to binary 'operator%'My code:
double to_positive_angle(double angle) { return ((3600000 + angle) % 360); } float to_positive_angle(float angle) { return ((3600000 + angle) % 360); }
Its obviously because I am trying to use the Modulus operator on a Float and Double.
Are the any ways I can successfully convert a negative angle (float) to a positive one (float)? Or ways that I can overcome the modulus compile error?
-
R.. GitHub STOP HELPING ICE almost 11 yearsThis is going to be terribly slow if
angle
is large, and might never terminate sinceangle+360==angle
is possible for largeangle
. -
Alan almost 11 years@R.. Great point. I didn't even consider large values of angle.
-
Mike Woolf almost 11 yearsOf course, the loop can be made faster yet stay general by adding 3600000 each time through, instead of 360. Why not?
-
R.. GitHub STOP HELPING ICE almost 11 yearsAdding 3600000 will destroy the precision, especially in the float version.
-
Ky - about 7 yearsI cannot vote this up, as it uses a loop when a single-step operation will suffice