sazr
sazr

Reputation: 25938

Convert negative angle to positive: Involves invalid operand use

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?

Upvotes: 5

Views: 19806

Answers (4)

aleio1
aleio1

Reputation: 94

I think this is the smartest way:

void get_positve_angle(double theta)
{
    return fmod(fmod(theta,360)+360,360);
}

Upvotes: 0

Alan
Alan

Reputation: 46883

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

Upvotes: 5

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215457

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

Upvotes: 14

paddy
paddy

Reputation: 63481

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.

Upvotes: 5

Related Questions