用C++实现对 3 个变量按由小到大顺序排序用不带默认参数的函数实现的代码
时间: 2024-05-10 20:20:02 浏览: 9
```
#include <stdio.h>
void sort(int a, int b, int c);
int main() {
int x = 3, y = 2, z = 1;
sort(x, y, z);
printf("%d %d %d\n", x, y, z);
return 0;
}
void sort(int a, int b, int c) {
if (a > b) {
int temp = a;
a = b;
b = temp;
}
if (a > c) {
int temp = a;
a = c;
c = temp;
}
if (b > c) {
int temp = b;
b = c;
c = temp;
}
}
```
相关问题
对 3 个变量按由小到大顺序排序 用带有默认参数的函数实现的C++代码
下面是一个用带有默认参数的函数实现对三个变量按由小到大顺序排序的C代码:
```c
#include <stdio.h>
void sort(int *a, int *b, int *c, int ascending_order = 1) {
int temp;
if (ascending_order) {
if (*a > *b) {
temp = *a;
*a = *b;
*b = temp;
}
if (*b > *c) {
temp = *b;
*b = *c;
*c = temp;
}
if (*a > *b) {
temp = *a;
*a = *b;
*b = temp;
}
} else {
if (*a < *b) {
temp = *a;
*a = *b;
*b = temp;
}
if (*b < *c) {
temp = *b;
*b = *c;
*c = temp;
}
if (*a < *b) {
temp = *a;
*a = *b;
*b = temp;
}
}
}
int main() {
int x = 3, y = 1, z = 2;
printf("Original order: x=%d, y=%d, z=%d\n", x, y, z);
sort(&x, &y, &z);
printf("Ascending order: x=%d, y=%d, z=%d\n", x, y, z);
sort(&x, &y, &z, 0);
printf("Descending order: x=%d, y=%d, z=%d\n", x, y, z);
return 0;
}
```
这个程序定义了一个名为 `sort` 的函数,它接受三个指向整数的指针作为参数,并且还有一个默认参数 `ascending_order`,默认值为 `1`,表示按升序排列。如果 `ascending_order` 的值为 `0`,则按降序排列。
在 `sort` 函数中,我们使用了一个简单的冒泡排序算法,先比较前两个数,然后比较后两个数,最后再比较前两个数,这样就可以把三个数按由小到大或由大到小的顺序排列好。
在 `main` 函数中,我们定义了三个变量 `x`、`y` 和 `z`,并且先输出它们的原始顺序。然后我们先调用 `sort` 函数,按升序排列这三个数,并输出结果;接着再次调用 `sort` 函数,按降序排列这三个数,并输出结果。
用C++对3个变量按由小到大顺序排序,要求使用变量的引用。
可以使用以下代码实现:
```cpp
#include <iostream>
using namespace std;
void sort(int& a, int& b, int& c) {
if (a > b) swap(a, b);
if (a > c) swap(a, c);
if (b > c) swap(b, c);
}
int main() {
int a = 3, b = 1, c = 2;
sort(a, b, c);
cout << a << " " << b << " " << c << endl; // 输出 1 2 3
return 0;
}
```
函数sort接受3个int类型的引用参数,通过比较大小交换变量的值,最终实现对3个变量按由小到大顺序排序。在主函数中调用sort函数并输出结果。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)