求模运算符 % modulus operator

只用于整数。

结果是左侧整数除以右侧整数的余数 remainder

#includeint main(void){int a = 8;int b = 3;printf("8 %% 3 = %d\n", a % b);return 0;}

结果:

8 % 3 = 2

求模运算符常用于控制程序流。

程序示例:

// 输入秒数,将其转换为分钟数和秒数#include#define SEC_PER_HOUR 60int main(void){printf("Enter the seconds (Enter q to quit): ");int seconds = 0;int min = 0;while (scanf("%d", &seconds) == 1){min = seconds / SEC_PER_HOUR;seconds = seconds % SEC_PER_HOUR;printf("minutes = %d, seconds = %d.\n", min, seconds);printf("Enter the seconds (Enter q to quit): ");}return 0;}

结果:

Enter the seconds (Enter q to quit): 121minutes = 2, seconds = 1.Enter the seconds (Enter q to quit): 23minutes = 0, seconds = 23.Enter the seconds (Enter q to quit): q

负整数求模

自从 C99 规定负整数除法是趋零截断后,负整数求模也只有一种结果。

负整数求模的结果的正负和第一个整数相同。

程序示例:

#includeint main(void){printf("-11 %% 5 = %d\n", (- 11) % 5);printf("-11 %% -5 = %d\n", (-11) % -5);printf("11 %% -5 = %d\n", 11 % -5);printf("11 %% 5 = %d\n", 11 % 5);return 0;}

结果:

-11 % 5 = -1-11 % -5 = -111 % -5 = 111 % 5 = 1