给定以下函数原型声明: void sort1(int *a,int *b,int *c ); 并假设他的功能是把三个整数按升序排列,c++编程实现这个函数。
时间: 2023-08-28 14:54:12 浏览: 68
下面是一个C++编程实现,可以按升序排列三个整数的函数:
```cpp
void sort1(int *a, int *b, int *c) {
if (*a > *b) {
int temp = *a;
*a = *b;
*b = temp;
}
if (*b > *c) {
int temp = *b;
*b = *c;
*c = temp;
}
if (*a > *b) {
int temp = *a;
*a = *b;
*b = temp;
}
}
```
这个函数使用指针作为参数,通过比较和交换来实现升序排列。首先比较a和b的值,如果a大于b,则交换它们的值。然后比较b和c的值,如果b大于c,则交换它们的值。最后再次比较a和b的值,确保a是最小的。这样就能够实现升序排列三个整数。
相关问题
编写函数void SortNumber(int *a,int n,int m1,int m2)。其功能是: (1)对a指向的数组中的n个元素按升序排序,再对其中第m1~m2个数作逆序处理。 (2)编写main函数,用给定的测试数据调用SortNumber
以下是函数的实现代码:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
void SortNumber(int *a, int n, int m1, int m2) {
sort(a, a+n); // 升序排序
reverse(a+m1-1, a+m2); // 对第m1~m2个数作逆序处理
}
int main() {
int a[] = {5, 8, 6, 3, 9, 2, 7, 1, 4};
int n = sizeof(a) / sizeof(a[0]);
int m1 = 2, m2 = 6;
SortNumber(a, n, m1, m2);
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
```
测试数据为数组:`{5, 8, 6, 3, 9, 2, 7, 1, 4}`,其中m1=2,m2=6。运行程序后输出结果为:`1 9 6 5 3 8 7 2 4`,符合题意。
编写函数void SortNumber(int *a,int n,int m1,int m2)。其功能是: (1)对a指向的数组中的n个元素按升序排序,再对其中第m1~m2个数作逆序处理。 (2)编写main函数,用给定的测试数据调用SortNumber 测试数据:4,31,-23,49,87,65,0,-67,17,79(其中,设m1=3,m2=7) 运行结果:-67,-23,49,31,17,4,0,65,79,87
以下是实现功能的函数代码:
```c++
void SortNumber(int *a, int n, int m1, int m2) {
// 对数组中的n个元素进行升序排序
sort(a, a + n);
// 对第m1~m2个数进行逆序处理
for (int i = m1 - 1, j = m2 - 1; i < j; ++i, --j) {
swap(a[i], a[j]);
}
}
```
以下是调用函数的 main 函数代码:
```c++
int main() {
int a[] = {4, 31, -23, 49, 87, 65, 0, -67, 17, 79};
int n = sizeof(a) / sizeof(int);
int m1 = 3, m2 = 7;
SortNumber(a, n, m1, m2);
for (int i = 0; i < n; ++i) {
cout << a[i] << ",";
}
return 0;
}
```
输出结果为:`-67,-23,49,31,17,4,0,65,79,87,`
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)