c++range# How to wrap around a range

Angles in my program are expressed in 0 to 2pi. I want a way to add two angles and have it wrap around the 2pi to 0 if the result is higher than 2pi. Or if I subtracted an angle from an angle and it was below 0 it would wrap around 2pi.

Is there a way to do this?

Thanks.

Solution

What you are looking for is the modulus. The fmod function will not work because it calculates the remainder and not the arithmetic modulus. Something like this should work:

```
inline double wrapAngle( double angle )
{
double twoPi = 2.0 * 3.141592865358979;
return angle - twoPi * floor( angle / twoPi );
}
```

Edit:

The remainder is commonly defined as what is left over after long division (eg. the remainder of 18/4 is 2, because **18 = 4 * 4 + 2**). This gets hairy when you have negative numbers. The common way to find the remainder of a signed division is for the remainder to have the same sign as the result (eg. the remainder of -18/4 is -2, because **-18 = -4 * 4 + -2**).

The definition of x modulus y is the smallest positive value of m in the equation x=y*c+m, given c is an integer. So **18 mod 4** would be 2 (where c=4), however **-18 mod 4** would also be 2 (where c=-5).

The simplest calculation of **x mod y** is **x-y*floor(x/y)**, where floor is the largest integer that is less than or equal to the input.

- How to get column of a multidimensional array in C/C++?
- In CMake, how can I test if the compiler is Clang?
- Find four,whose sum equals to target
- Can't make MSMPI to work. It always says "mpi.h: No such file or directory gcc"
- Do all C compilers implicitly drop the fractional when converting floating point to integer?
- Message Queue (mqueue.h), Invalid Argument Error, In C
- Undefined Macro in #if directive?
- C/C++: How to use the do-while(0); construct without compiler warnings like C4127?
- Minimum number of phones
- Nesting Structs in C
- Visual Studio Code for some reason changes '\' with '/' in Include Path
- Generating all divisors of a number given its prime factorization
- sizeof single struct member in C
- Memory usage isn't decreasing when using free?
- Why are all the strings the same
- strstr issue in C
- In C macros, should one prefer do { ... } while(0,0) over do { ... } while(0)?
- Union initialization in C++ and C
- Trying to store strings returned by strsep gives seg fault
- C pointer address printing
- strcmp or string::compare?
- What is proper name for the WINAPI tag in a c function?
- Need help in understanding the Capsicum capability mode and its effect on getpass()
- Force a program created using `exec` to perform unbuffered I/O
- How to display characters in a write() funtion C
- Declaring extern structures in header file in C
- match files .c on tasks.json to compile
- Replacing spaces with %20 in C
- What does the comma operator , do?
- How to build multiple targets from one makefile