C 语言中的取模运算符

本文将演示如何在 C 语言中使用取模运算符的多种方法。
在 C 语言中使用%
取模运算符计算除法中的余数
取模运算符%
是 C 语言中的二进制算术运算符之一。它产生两个给定数字相除后的余数。取模运算符不能应用于浮点数,如 float
或 double
。在下面的示例代码中,我们展示了使用%
运算符的最简单例子,打印给定的 int
数组的对 9 取模的结果。
#include <stdio.h> #include <stdlib.h> int main(void) { int arr[8] = {10, 24, 17, 35, 65, 89, 55, 77}; for (int i = 0; i < 8; ++i) { printf("%d/%d yields the remainder of - %d\n", arr[i], 9, arr[i] % 9); } exit(EXIT_SUCCESS); }
输出:
10/9 yields the remainder of - 1 24/9 yields the remainder of - 6 17/9 yields the remainder of - 8 35/9 yields the remainder of - 8 65/9 yields the remainder of - 2 89/9 yields the remainder of - 8 55/9 yields the remainder of - 1 77/9 yields the remainder of - 5
使用%
取模运算符在 C 语言中实现闰年校验功能
另外,我们也可以使用%
运算符来实现更复杂的函数。下一个示例代码演示了 isLeapYear
布尔函数,它检查给定的年份是否是闰年。需要注意的是,如果一个年份的值被 4 整除但不被 100 整除,那么这个年份就被认为是闰年。此外,如果年值被 400 整除,它就是一个闰年。
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> bool isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) return true; else return false; } int main(void) { uint year = 2021; isLeapYear(year) ? printf("%d is leap\n", year) : printf("%d is not leap\n", year); exit(EXIT_SUCCESS); }
输出:
2021 is not leap
C 语言中使用%
取模运算符在给定的整数范围内生成随机数
取模运算符的另一个有用的功能是在随机数生成过程中限制数字的上限。也就是说,假设我们有一个生成随机整数的函数。在这种情况下,我们可以把返回的数和我们需要的值之间的除数的剩余部分作为最大值(在下面的例子中定义为 MAX
宏)。需要注意的是,使用 srand
和 rand
函数来生成随机数并不是一种稳健的方法,需要高质量随机数的应用应该采用其他工具。
#include <stdio.h> #include <stdlib.h> #include <time.h> #define COUNT 10 #define MAX 100 int main(void) { srand(time(NULL)); for (int i = 0; i < COUNT; i++) { printf("%d, ", rand() % MAX); } printf("\b\b \n"); exit(EXIT_SUCCESS); }
输出:
3, 76, 74, 93, 51, 65, 76, 31, 61, 97
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu