编写一个程序,用取余运算和位运算判断整数的奇偶。
时间: 2023-05-28 16:02:31 浏览: 66
#include <iostream>
using namespace std;
int main() {
int num;
cout << "请输入一个整数:";
cin >> num;
if (num & 1) {
cout << "该整数是奇数。" << endl;
} else {
cout << "该整数是偶数。" << endl;
}
return 0;
}
//输出结果:
//请输入一个整数:7
//该整数是奇数。
相关问题
c++编写一个程序,用取余运算和位运算判断整数的奇偶。
#include <stdio.h>
int main() {
int a;
printf("请输入一个整数:");
scanf("%d", &a);
if (a % 2 == 0) {
printf("%d是偶数\n", a);
} else {
printf("%d是奇数\n", a);
}
if (a & 1) {
printf("使用位运算,%d是奇数\n", a);
} else {
printf("使用位运算,%d是偶数\n", a);
}
return 0;
}
判断奇偶性用位运算c语言程序
在C语言中,可以使用位运算来判断一个整数的奇偶性。具体方法是将该整数转换为二进制数,然后判断其最低位是否为1。如果最低位为1,则该整数为奇数,否则为偶数。以下是一个示例程序:
```
#include <stdio.h>
int isOdd(int n){
return n & 1;
}
int main(int argc, char const *argv[]) {
for (int i = -10; i < 10; ++i) {
if (isOdd(i)) {
printf("%d: %s\n", i, "奇数");
} else {
printf("%d: %s\n", i, "偶数");
}
}
return 0;
}
```
在上面的程序中,函数isOdd()用于判断一个整数是否为奇数,其中&运算符表示按位与运算。在主函数中,我们对-10到9之间的整数进行了奇偶性判断,并输出了结果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)