编程中模数(%)的实际用途是什么? [英] What are the practical uses of modulus (%) in programming?
本文介绍了编程中模数(%)的实际用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
识别何时使用mod运算符
Possible Duplicate:
Recognizing when to use the mod operator
模数的实际用途是什么?我知道什么是模除法.我想到的第一种情况是使用它来查找奇数和偶数以及时钟算术.但是我还能在其他地方使用它吗?
What are the practical uses of modulus? I know what modulo division is. The first scenario which comes to my mind is to use it to find odd and even numbers, and clock arithmetic. But where else I could use it?
推荐答案
我发现最常见的用途是包装"您的数组索引.
The most common use I've found is for "wrapping round" your array indices.
例如,如果您只想重复循环遍历一个数组,则可以使用:
For example, if you just want to cycle through an array repeatedly, you could use:
int a[10];
for (int i = 0; true; i = (i + 1) % 10)
{
// ... use a[i] ...
}
取模确保i
保持在[0,10)范围内.
The modulo ensures that i
stays in the [0, 10) range.
这篇关于编程中模数(%)的实际用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文