首页 > 文章列表 > C程序打印“偶数”或“奇数”,不使用条件语句

C程序打印“偶数”或“奇数”,不使用条件语句

条件语句 打印 C程序 偶数 奇数
443 2023-08-20

在本节中,我们将看到如何在不使用任何条件语句(如<,<=,!=,>,>=,==)的情况下检查一个数是奇数还是偶数。

我们可以通过使用条件语句轻松地检查奇数还是偶数。我们可以将数字除以2,然后检查余数是否为0。如果为0,则是偶数。否则,我们可以将数字与1进行AND运算。如果答案为0,则是偶数,否则为奇数。

这里不能使用条件语句。我们将看到两种不同的方法来检查奇数还是偶数。

方法1

在这里,我们将创建一个字符串数组。索引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
}

Output 1

的中文翻译为:

输出 1

Enter a number: 40
The number is: Even

输出 2

Enter a number: 89
The number is: Odd

方法2

这是第二种方法。在这种方法中,我们将使用一些技巧。这里使用了逻辑和位运算符。首先,我们对数字和1进行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.
}

Output 1

的中文翻译为:

输出 1

Enter a number: 40
even

输出 2

Enter a number: 89
odd