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

在本节中,我们将了解如何在不使用任何类型的条件语句(例如(<,<=,!=,>,> =,==))的情况下检查数字是奇数还是偶数。

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

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

方法1

在这里,我们将创建一个字符串数组。索引0的位置将保持“偶数”,索引1的位置将保持“奇数”。将数字除以2后,我们可以发送余数作为索引直接获得结果。

范例程式码

#include <iostream>
using namespace std;
main() {
   int n;
   string arr[2] = {"Even", "Odd"};
   cout << "Enter a number: "; //take the number from the user
   cin >> n;
   cout << "The number is: " << 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

方法2

这是第二种方法。在这种方法中,我们将使用一些技巧。这里使用逻辑和按位运算符。首先,我们使用数字和1进行“与”运算,然后使用逻辑和打印奇数或偶数。当按位与的结果为1时,仅逻辑与运算将返回奇数结果,否则将返回偶数。

范例程式码

#include <iostream>
using namespace std;
main() {
   int n;
   string arr[2] = {"Even", "Odd"};
   cout << "Enter a number: "; //take the number from the user
   cin >> n;
   (n & 1 && cout << "odd")|| cout << "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