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
-
1your code works when I run it. (Aside from modifications to not use NSLog.) Can you try to produce a minimal test case that does reproduce the problem?Winston Ewert– Winston Ewert2010年11月26日 16:34:00 +00:00Commented Nov 26, 2010 at 16:34
-
1Prints "176400" or "1764000"? Also, including that for loop would be helpful.darioo– darioo2010年11月26日 16:36:09 +00:00Commented Nov 26, 2010 at 16:36
-
The code you show looks fine, the problem may be in the loop around it, or somewhere else. Please post the full code (and avoid things like NSLog, or tag Xcode, that's XCode specific, not C).kriss– kriss2010年11月26日 16:47:52 +00:00Commented Nov 26, 2010 at 16:47
3 Answers 3
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.
4 Comments
count is way bigger than we're expecting it to be.count == 11?Your doing "n modulo m" where m is bigger than n. The result is n, and it's correct.
Maybe you wanted count % blah?
6 Comments
count % blah makes more sense in most situations i can think of.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.