用C++写一个四个整数的排序
时间: 2023-05-26 14:01:53 浏览: 65
一种实现方法如下,使用冒泡排序算法:
```c
#include <stdio.h>
int main() {
int a, b, c, d;
printf("请输入四个整数:\n");
scanf("%d%d%d%d", &a, &b, &c, &d);
int array[4] = {a, b, c, d};
// 冒泡排序
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
// 输出排序后的结果
printf("排序后的结果为:\n");
for (int i = 0; i < 4; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
```
运行程序后,输入四个整数,程序会输出排序后的结果。
相关问题
用c++写一个输入四个整数从小到大顺序和从大到小顺序输出
以下是用C语言编写的程序,可以输入四个整数并按从小到大和从大到小顺序输出:
#include <stdio.h>
int main()
{
int a, b, c, d;
printf("请输入四个整数:\n");
scanf("%d%d%d%d", &a, &b, &c, &d);
int arr[4] = {a, b, c, d};
int i, j, temp;
// 从小到大排序
for (i = 0; i < 3; i++)
for (j = i + 1; j < 4; j++)
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
printf("从小到大顺序:");
for (i = 0; i < 4; i++)
printf("%d ", arr[i]);
printf("\n");
// 从大到小排序
for (i = 0; i < 3; i++)
for (j = i + 1; j < 4; j++)
if (arr[i] < arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
printf("从大到小顺序:");
for (i = 0; i < 4; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
四个整数从小到大排序,并用sort函数
C++代码如下:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a = 2, b = 4, c = 1, d = 3;
int arr[] = {a, b, c, d};
sort(arr, arr + 4);
for (int i = 0; i < 4; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:
```
1 2 3 4
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)