Link to home
Start Free TrialLog in
Avatar of slavikn
slavikn

asked on

Imitating % for ints

Hi,

I need to imitate the '%' operator that C offers.
But I also need it to work with floats.
The floats isn't the problem.
What I need it the code that imitates '%' (for negative number too, of course).

Thanks in advance.
Avatar of Sjef Bosman
Sjef Bosman
Flag of France image

How far did you get yourself? Converting a number to a string isn't too difficult.
Avatar of slavikn
slavikn

ASKER

strings? hmm....

while (a >= b)
   a -= b;

but this doesn't work if a and b are negative.
ASKER CERTIFIED SOLUTION
Avatar of Sjef Bosman
Sjef Bosman
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of slavikn

ASKER

> Try if it works for negative numbers.

Yes, it does. Thanks!
Avatar of slavikn

ASKER

heh   :-D
'fmod' from 'math.h' does exactly the same  :-))
'man pages' say it uses same formula  :-))
They didn't get it from me ;-)  Nor did I do a man fmod, but maybe I will...
Avatar of slavikn

ASKER

Heh ;-)   I wrote this to say two things:
1) your formula is correct.
2) I could use a ready-made function instead.
:-)))
Better to use fmod, since converting to int will not work for numbers that go beyond integer precision. Probably fmod is then defined as a-floor(a/b)*b. Or so.

Sjef :)