x
Solved

# Imitating % for ints

Posted on 2004-09-13
Medium Priority
256 Views
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).

0
Question by:slavikn
• 4
• 4

LVL 46

Expert Comment

ID: 12043191
How far did you get yourself? Converting a number to a string isn't too difficult.
0

LVL 1

Author Comment

ID: 12043207
strings? hmm....

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

but this doesn't work if a and b are negative.
0

LVL 46

Accepted Solution

Sjef Bosman earned 100 total points
ID: 12043260
Ahem :-\$ sorry! I thought you meant the % in printf... Never mind...

a%b = a-(int)(a/b)*b

where \ is the integer divide operator. Try if it works for negative numbers.
0

LVL 1

Author Comment

ID: 12043509
> Try if it works for negative numbers.

Yes, it does. Thanks!
0

LVL 1

Author Comment

ID: 12045120
heh   :-D
'fmod' from 'math.h' does exactly the same  :-))
'man pages' say it uses same formula  :-))
0

LVL 46

Expert Comment

ID: 12045371
They didn't get it from me ;-)  Nor did I do a man fmod, but maybe I will...
0

LVL 1

Author Comment

ID: 12045445
Heh ;-)   I wrote this to say two things:
:-)))
0

LVL 46

Expert Comment

ID: 12045663
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 :)
0

## Featured Post

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.