Sign in to follow this  
Sync Views

make numbers wrap around

Recommended Posts

Sync Views    139
How can I make a double or int wrap around between 0 <= x < 360 So x would go to y
x     -> y
-90   -> 270
360   -> 0
-180  -> 180
-45   -> 315
etc
I know I can do it by a loop but is there a better way for wrapping numbers around?
double WrapDeg(double Dir)
{
	while(Dir <  0)   Dir += 360;
	while(Dir >= 360) Dir -= 360;
	return Dir;
}

Share this post


Link to post
Share on other sites
fpsgamer    856
Quote:
Original post by Sync Views
How can I make a double or int wrap around between 0 <= x < 360


Assuming C++...

#include <cmath>
...
double wrappedValue = fmod (value,360.0); // modulo for real (eg. float or double) values

Share this post


Link to post
Share on other sites
fpsgamer    856
Quote:
Original post by blueapple
Instead of using loops, you could use the modulus operator (%):
int angle = 725;
angle = angle % 360; // angle is now 25
angle = angle % 360; // angle is still 25


That won't work.

The modulo operator only works for integral types. The OP specified he is using doubles. Use fmod() for real (eg. floating point) valued types.

Share this post


Link to post
Share on other sites
blueapple    162
Well, actually, he asked:
Quote:
Original post by Sync Views
How can I make a double or int wrap around between 0 <= x < 360

But you're right, for doubles, it won't work (and I'm not sure about negative numbers).

Share this post


Link to post
Share on other sites
fpsgamer    856
Quote:
Original post by blueapple
Well, actually, he asked:
Quote:
Original post by Sync Views
How can I make a double or int wrap around between 0 <= x < 360

But you're right, for doubles, it won't work (and I'm not sure about negative numbers).


My bad. I cant read :)

Share this post


Link to post
Share on other sites
thre3dee    100
Quote:
Original post by blueapple
Instead of using loops, you could use the modulus operator (%):
int angle = 725;
angle = angle % 360; // angle is now 25
angle = angle % 360; // angle is still 25


Actually the angle is 5º (2×360º=720º)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this