C++程序:检查数字是偶数还是奇数


如果一个数字能被2整除,则它是偶数;如果不能被2整除,则它是奇数。

一些偶数包括:

2, 4, 6, 8, 10, 12, 14, 16

一些奇数包括:

1, 3, 5, 7, 9, 11, 13, 15, 17

使用取模运算符检查数字是偶数还是奇数

以下是使用取模运算符检查数字是偶数还是奇数的程序。

示例

 在线演示

#include <iostream>
using namespace std;
int main() {
   int num = 25;
   if(num % 2 == 0)
   cout<<num<<" is even";
   else
   cout<<num<<" is odd";
   return 0;
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

25 is odd

在上面的程序中,数字num被2除,并观察其余数。如果余数为0,则该数字为偶数;如果余数为1,则该数字为奇数。

if(num % 2 == 0)
   cout<<num<<" is even";
else
   cout<<num<<" is odd";

使用按位与运算符检查数字是偶数还是奇数

如果一个数字在二进制表示中其最右边的位为1,则它是奇数;如果其最右边的位为0,则它是偶数。这可以通过对数字和1进行按位与运算来找到。如果结果为0,则该数字为偶数;如果结果为1,则该数字为奇数。

以下是使用按位与运算符检查数字是偶数还是奇数的程序:

示例

 在线演示

#include <iostream>
using namespace std;
int main() {
   int num = 7;
   if((num & 1) == 0)
   cout<<num<<" is even";
   else
   cout<<num<<" is odd";
   return 0;
}

输出

7 is odd

在上面的程序中,对num和1进行按位与运算。如果结果为0,则num为偶数;否则,num为奇数。

if((num & 1) == 0)
cout<<num<<" is even";
else
cout<<num<<" is odd";

更新于:2020年6月24日

13K+ 浏览量

开启你的职业生涯

通过完成课程获得认证

开始学习
广告