c++编写一个程序,用取余运算和位运算判断整数的奇偶。
时间: 2023-05-26 13:04:35 浏览: 57
#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进行"与"运算,如果结果为0,则表示该数是偶数;如果结果为1,则表示该数是奇数。
以下是一个示例代码:
```cpp
#include <iostream>
using namespace std;
int main() {
int num;
cout << "请输入一个整数:" << endl;
cin >> num;
if ((num & 1) == 0) {
cout << "输入的数是偶数" << endl;
} else {
cout << "输入的数是奇数" << endl;
}
return 0;
}
```
在这个示例代码中,我们首先输入一个整数,然后使用位运算符"&"将该数与1进行运算。如果结果为0,则输出"输入的数是偶数";如果结果为1,则输出"输入的数是奇数"。这样就可以通过位运算来判断一个数是奇数还是偶数。\[1\]\[2\]\[3\]
#### 引用[.reference_title]
- *1* *3* [C++中运算符优先级及位运算判断奇偶性](https://blog.csdn.net/secular_/article/details/85262491)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [C++ 使用位运算判断整数的奇偶性](https://blog.csdn.net/liu_feng_zi_/article/details/107974319)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
给定n个整数,请统计奇数和偶数各有多少个
算法1:遍历
遍历整个数组,统计奇数和偶数的个数。
时间复杂度:O(n)
C++ 代码
```
#include <iostream>
using namespace std;
int main() {
int n, num, odd = 0, even = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num;
if (num % 2 == 0) {
even++;
} else {
odd++;
}
}
cout << "Odd: " << odd << endl;
cout << "Even: " << even << endl;
return 0;
}
```
算法2:位运算
奇数二进制的最后一位是1,偶数二进制的最后一位是0。因此可以通过位运算来判断奇偶性。
时间复杂度:O(n)
C++ 代码
```
#include <iostream>
using namespace std;
int main() {
int n, num, odd = 0, even = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num;
if (num & 1) {
odd++;
} else {
even++;
}
}
cout << "Odd: " << odd << endl;
cout << "Even: " << even << endl;
return 0;
}
```
相关推荐
![](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)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)