Public Group

# make numbers wrap around

This topic is 3720 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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 on other sites
Quote:
 Original post by Sync ViewsHow 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 on other sites
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

##### Share on other sites
Quote:
 Original post by blueappleInstead 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.

##### Share on other sites
Quote:
 Original post by Sync ViewsHow 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 on other sites
Quote:
Original post by blueapple
Quote:
 Original post by Sync ViewsHow 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 on other sites
Quote:
 Original post by blueappleInstead 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º)

1. 1
2. 2
Rutin
24
3. 3
4. 4
JoeJ
16
5. 5

• 14
• 29
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631775
• Total Posts
3002275
×