無需條件語句判斷奇偶數的C語言程式
在本節中,我們將學習如何在不使用任何條件語句(如 <、<=、!=、>、>=、==)的情況下檢查一個數字是奇數還是偶數。
我們可以很容易地使用條件語句來檢查奇偶數。我們可以將數字除以2,然後檢查餘數是否為0。如果為0,則為偶數;否則,我們可以對數字執行與1的AND運算。如果結果為0,則為偶數,否則為奇數。
這裡不能使用任何條件語句。我們將看到兩種不同的方法來檢查奇偶數。
方法一
在這裡,我們將建立一個字串陣列。索引0位置將儲存“偶數”,索引1位置將儲存“奇數”。我們可以將數字除以2後的餘數作為索引直接獲取結果。
示例程式碼
#include<stdio.h> main() { int n; char* arr[2] = {"Even", "Odd"}; printf("Enter a number: "); //take the number from the user scanf("%d", &n); printf("The number is: %s", arr[n%2]); //get the remainder to choose the string }
輸出1
Enter a number: 40 The number is: Even
輸出2
Enter a number: 89 The number is: Odd
方法二
這是第二種方法。在這種方法中,我們將使用一些技巧。這裡使用了邏輯和位運算子。首先,我們對數字和1進行AND運算。然後使用邏輯與來列印奇數或偶數。當位運算AND的結果為1時,只有邏輯AND運算才會返回奇數結果,否則它將返回偶數。
示例程式碼
#include<stdio.h> main() { int n; char *arr[2] = {"Even", "Odd"}; printf("Enter a number: "); //take the number from the user scanf("%d", &n); (n & 1 && printf("odd"))|| printf("even"); //n & 1 will be 1 when 1 is present at LSb, so it is odd. }
輸出1
Enter a number: 40 even
輸出2
Enter a number: 89 odd
廣告