dubbeat
dubbeat

Reputation: 7857

problem using mod operator c

I'm trying to perform a mod (%) on 2 ints in c. My first time attempting such a thing.

The code below is in a loop where count is set to 0 outside the loop and increments by 1 every iteration. I'm expecting to see my "read" value change but it stays stuck at the value for "blah".

What am I doing wrong?

int blah=176400;
count+=1;
NSLog(@"the time = %i",count);// prints the correct increments
int read = (int)(blah % count);
NSLog(@"read %i",read); // prints out 1764000 all the time

Upvotes: 0

Views: 9927

Answers (3)

cHao
cHao

Reputation: 86575

Understand that blah % count is basically the remainder from dividing blah by count, if both numbers are positive. (Things get a bit hairier when one or both of the numbers are negative.) If count is the larger number, then the result will always be blah (as the division would yield 0, with a remainder of blah). In your case it seems that count is getting very large, leading to this very situation.

It's hard to divine the intent of your using % here, but it seems that either your operands are in the wrong order, or you're misunderstanding what the result should be...or perhaps, that what you actually need is a different operator entirely.

Upvotes: 1

Steve Jessop
Steve Jessop

Reputation: 279385

Example code:

#include <stdio.h>

int main() {
    int blah = 176400;
    for (int count = 1; count < 20; ++count) {
        printf("%d %% %d = %d\n", blah, count, blah % count);
    }
}

Output:

176400 % 1 = 0
176400 % 2 = 0
176400 % 3 = 0
176400 % 4 = 0
176400 % 5 = 0
176400 % 6 = 0
176400 % 7 = 0
176400 % 8 = 0
176400 % 9 = 0
176400 % 10 = 0
176400 % 11 = 4
176400 % 12 = 0
176400 % 13 = 3
176400 % 14 = 0
176400 % 15 = 0
176400 % 16 = 0
176400 % 17 = 8
176400 % 18 = 0
176400 % 19 = 4

I'd say the problem is elsewhere in your code.

Upvotes: 4

F&#39;x
F&#39;x

Reputation: 12328

Your doing "n modulo m" where m is bigger than n. The result is n, and it's correct.

Maybe you wanted count % blah?

Upvotes: 1

Related Questions