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