可能重复:
识别何时使用mod运算符
模数的实际用途是什么?我知道模数除法是什么.我想到的第一个场景是使用它来查找奇数和偶数,以及时钟算术.但在哪里我可以使用它?
Pet*_*der 23
我发现最常见的用途是"包裹"你的数组索引.
例如,如果您只想重复循环一个数组,可以使用:
int a[10];
for (int i = 0; true; i = (i + 1) % 10)
{
  // ... use a[i] ...
}
模数确保i保持在[0,10]范围内.
要将数字打印为字符串,您需要使用模数来查找数字的值.
string number_to_string(uint number) {
  string result = "";
  while (number != 0) {
    result = cast(char)((number % 10) + '0') ~ result;
    //                   ^^^^^^^^^^^
    number /= 10;
  }
  return result;
}
我通常在紧密循环中使用它们,当我必须在每个X循环中执行某些操作而不是在每次迭代时.
例:
int i;
for (i = 1; i <= 1000000; i++)
{
   do_something(i);
   if (i % 1000 == 0)
       printf("%d processed\n", i);
}
小智 5
对于国际银行账号的控制号,mod97技术。
也可以大批量的做一些n迭代之后的事情。这是NHibernate的示例:
ISession session = sessionFactory.openSession();
ITransaction tx = session.BeginTransaction();
for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.Save(customer);
    if ( i % 20 == 0 ) { //20, same as the ADO batch size
        //Flush a batch of inserts and release memory:
        session.Flush();
        session.Clear();
    }
}
tx.Commit();
session.Close();