make numbers wrap around

Started by
5 comments, last by thre3dee 15 years, 11 months ago
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;
}
Advertisement
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
Instead of using loops, you could use the modulus operator (%):
int angle = 725;angle = angle % 360; // angle is now 25angle = angle % 360; // angle is still 25
Check out my devlog.
Quote:Original post by blueapple
Instead of using loops, you could use the modulus operator (%):
int angle = 725;angle = angle % 360; // angle is now 25angle = 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.
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).
Check out my devlog.
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 :)
Quote:Original post by blueapple
Instead of using loops, you could use the modulus operator (%):
int angle = 725;angle = angle % 360; // angle is now 25angle = angle % 360; // angle is still 25


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

This topic is closed to new replies.

Advertisement