在本节中,我们将了解如何在不使用任何类型的条件语句(例如(<,<=,!=,>,> =,==))的情况下检查数字是奇数还是偶数。
我们可以使用条件语句轻松检查奇数或偶数。我们可以将数字除以2,然后检查余数是否为0。如果为0,则为偶数。否则,我们可以使用数字和1进行与运算。如果答案为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 }
Enter a number: 40 The number is: Even
Enter a number: 89 The number is: Odd
这是第二种方法。在这种方法中,我们将使用一些技巧。这里使用逻辑和按位运算符。首先,我们使用数字和1进行“与”运算,然后使用逻辑和打印奇数或偶数。当按位与的结果为1时,仅逻辑与运算将返回奇数结果,否则将返回偶数。
#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. }
Enter a number: 40 even
Enter a number: 89 odd