c++输入10个整数,完成一个函数使数据 重新排序以后输出(也按空格分隔),要求: 输出奇数在前偶数在后 函数接口定义: void sort_tarray ( int* a );
时间: 2023-06-11 20:10:30 浏览: 73
以下是实现该函数的代码:
```c
#include <stdio.h>
void sort_tarray(int *a) {
int i, j, temp;
for (i = 0; i < 10; i++) {
for (j = i + 1; j < 10; j++) {
if (*(a + i) % 2 == 0 && *(a + j) % 2 != 0) {
temp = *(a + i);
*(a + i) = *(a + j);
*(a + j) = temp;
}
}
}
for (i = 0; i < 10; i++) {
printf("%d ", *(a + i));
}
}
int main() {
int arr[10], i;
printf("请输入10个整数:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
sort_tarray(arr);
return 0;
}
```
函数的实现使用了冒泡排序的思想,将奇数向前移动,偶数向后移动,最终输出排好序的整数数组。在主函数中先读入了10个整数,然后调用 `sort_tarray` 函数进行排序,最后输出排好序的数组。
相关问题
输入10个整数,完成一个函数使数据 重新排序以后输出(也按空格分隔),要求: 输出奇数在前偶数在后 函数接口定义: void sort_tarray ( int* a );
下面是一个简单的实现,思路是先把奇数和偶数分别取出来,然后再合并起来:
```c++
void sort_tarray(int* a) {
int oddCount = 0; // 奇数个数
int evenCount = 0; // 偶数个数
int* oddArray = new int[10]; // 存放奇数的数组
int* evenArray = new int[10]; // 存放偶数的数组
// 分离奇数和偶数
for (int i = 0; i < 10; i++) {
if (a[i] % 2 == 0) {
evenArray[evenCount++] = a[i];
}
else {
oddArray[oddCount++] = a[i];
}
}
// 合并奇数和偶数
for (int i = 0; i < oddCount; i++) {
a[i] = oddArray[i];
}
for (int i = 0; i < evenCount; i++) {
a[oddCount + i] = evenArray[i];
}
delete[] oddArray;
delete[] evenArray;
}
```
这个函数会把传入的数组按照奇数和偶数分别排序,奇数在前偶数在后。你可以这样调用它:
```c++
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
sort_tarray(a);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
```
输出结果为:
```
1 3 5 7 9 2 4 6 8 10
```
c++编写一个判断奇偶数的函数,在主函数由键盘输入一个整数调用函数输出,其为奇数还是偶数?
```c
#include <stdio.h>
int isOdd(int num) {
if (num % 2 == 0) {
return 0; // 偶数
} else {
return 1; // 奇数
}
}
int main() {
int num;
printf("请输入一个整数:");
scanf("%d", &num);
if (isOdd(num)) {
printf("%d是奇数", num);
} else {
printf("%d是偶数", num);
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)