使用 mod 运算符 c 时出现问题
我正在尝试对 c 中的 2 个整数执行 mod (%)。我第一次尝试这样的事情。
下面的代码位于一个循环中,其中 count 在循环外设置为 0,并在每次迭代时加 1。我期望看到我的“读取”值发生变化,但它仍然停留在“blah”值。
我做错了什么?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
示例代码:
输出:
我想说问题出在代码的其他地方。
Example code:
Output:
I'd say the problem is elsewhere in your code.
你在做“n modulo m”,其中m大于n。结果是n,正确。
也许您想要
count % blah
?Your doing "n modulo m" where m is bigger than n. The result is n, and it's correct.
Maybe you wanted
count % blah
?了解
blah % count
基本上是blah
除以count
的余数(如果两个数字均为正数)。 (当一个或两个数字都是负数时,事情会变得有点棘手。)如果count
是较大的数字,那么结果将始终是blah
(因为除法会产生 0,余数为blah
)。在您的情况下,似乎count
变得非常大,导致了这种情况。很难猜测您在这里使用
%
的意图,但似乎您的操作数顺序错误,或者您误解了结果应该是什么......或者也许,什么您实际上需要的是完全不同的运算符。Understand that
blah % count
is basically the remainder from dividingblah
bycount
, if both numbers are positive. (Things get a bit hairier when one or both of the numbers are negative.) Ifcount
is the larger number, then the result will always beblah
(as the division would yield 0, with a remainder ofblah
). In your case it seems thatcount
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.