Java -> C++ Modulo %

I’m sort of stuck on this. How would i get the modulo of a float in C++?

In Java for example you would do this:

float x = 6.5f;
float m = x % 3.0f; // 0.5

I looked into modf, but it doesn’t seem to do what I want. Any ideas?

thanks
ryan

I’m sure there is a better way then this, but I always do this with a while loop:

  
float x = 6.5f;  
float m = x;  
float modAmount = 3;  
while (m > modAmount) m -= modAmount;  
while (m < modAmount) m += modAmount;  
  
  

which does a floating point mod, and handles negative numbers also (which is useful for angles, etc).

does that work for you?

take care,
zach

ps: after googling, looks like there is also modf:
http://www.cplusplus.com/reference/clibrary/cmath/modf/
(actually not – I skimmed it, this is just for splitting off the fractional part of a float… what grimus posts below is what you want…)

I think fmod is what you want:

http://www.cplusplus.com/reference/clibrary/cmath/fmod/

Zach, yeah that’s what I ended up doing as a temporary solution, I was just wondering if there’s a better, more efficient way to do it since modulo is something I use a lot.

Grimus, thanks!

fmod NOT modf… confusing! but this looks like it’s he right thing.

ryan

there’s also remainder()… if you’re on a linux/osx system pop up a terminal and type ‘man remainder’