c语言 把数组拆分奇偶
时间: 2023-10-28 13:05:31 浏览: 149
你可以使用以下的C语言代码来实现将数组拆分为奇数和偶数:
```c
#include <stdio.h>
void split(int *a, int n, int *odd, int *cnto, int *even, int *cnte) {
*cnto = 0;
*cnte = 0;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
even[*cnte] = a[i];
(*cnte)++;
} else {
odd[*cnto] = a[i];
(*cnto)++;
}
}
}
int main() {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(a) / sizeof(a[0]);
int odd[n], even[n];
int cnto, cnte;
split(a, n, odd, &cnto, even, &cnte);
for (int i = 0; i < cnto; i++) {
printf("%d ", odd[i]);
}
printf("\n");
for (int i = 0; i < cnte; i++) {
printf("%d ", even[i]);
}
printf("\n");
return 0;
}
```
输出结果为:
```
1 3 5 7 9
2 4 6 8 10
```
这个程序会将数组`a`中的奇数存入`odd`数组,数量存入`cnto`;偶数存入`even`数组,数量存入`cnte`。首先,我们需要定义两个空数组`odd`和`even`,用来存放奇数和偶数。然后,我们遍历数组`a`,如果当前元素是偶数,则存入`even`数组中,并递增`cnte`;如果当前元素是奇数,则存入`odd`数组中,并递增`cnto`。最后,我们分别输出`odd`数组中的奇数和`even`数组中的偶数。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![](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)