目录
1. 基本定义
-
作用:取模运算符
%
返回两个整数相除后的余数。 -
语法:
result = dividend % divisor;
-
规则:
-
若
dividend
能被divisor
整除,结果为0
(例如15 % 5 = 0
)。 -
余数的符号与
dividend
(被除数)一致(例如-10 % 3 = -1
)。
-
2. 代码实例
示例 1:基础用法
#include <iostream>
using namespace std;
int main()
{
int B = 15, A = 5;
cout << B << " % " << A << " = " << B % A << endl; // 输出:15 % 5 = 0
int C = 10, D = 3;
cout << C << " % " << D << " = " << C % D << endl; // 输出:10 % 3 = 1
return 0;
}
示例 2:判断奇偶性
int num = 7;
if (num % 2 == 0)
{
cout << num << " 是偶数" << endl;
} else
{
cout << num << " 是奇数" << endl; // 输出:7 是奇数
}
示例 3:周期性操作(每 5 次换行)
for (int i = 1; i <= 10; i++)
{
cout << i << " ";
if (i % 5 == 0)
{
cout << endl; // 输出:1 2 3 4 5 \n6 7 8 9 10
}
}
3. 注意事项
-
操作数必须为整数:
// double x = 10.5, y = 3.0; // cout << x % y; // 错误:% 不能用于浮点数
-
除数不能为 0:
int E = 5, F = 0; // cout << E % F; // 运行时错误:除数为 0
-
负数取模规则:
cout << -10 % 3 << endl; // 输出:-1(余数符号与被除数一致) cout << 10 % -3 << endl; // 输出:1
4. 典型应用场景
-
循环队列索引:
int index = (current_index + 1) % buffer_size; // 环形缓冲区
-
哈希函数:
int hash = key % TABLE_SIZE; // 简单哈希映射
-
时间转换:
int total_seconds = 7265; int minutes = total_seconds / 60; // 121 分钟 int seconds = total_seconds % 60; // 5 秒
总结表格
表达式 | 结果 | 说明 |
---|---|---|
15 % 5 | 0 | 被除数能被除数整除 |
10 % 3 | 1 | 常规余数计算 |
-10 % 3 | -1 | 余数符号与被除数一致 |
10 % -3 | 1 | 余数符号仍与被除数一致 |
5 % 0 | 错误 | 除数为 0 会导致运行时错误 |