用c++写一个输入四个整数从小到大顺序输出
时间: 2023-05-24 20:02:18 浏览: 113
当然可以!以下是代码实现:
```c
#include <stdio.h>
int main() {
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
if(a > b) { int t = a; a = b; b = t; }
if(a > c) { int t = a; a = c; c = t; }
if(a > d) { int t = a; a = d; d = t; }
if(b > c) { int t = b; b = c; c = t; }
if(b > d) { int t = b; b = d; d = t; }
if(c > d) { int t = c; c = d; d = t; }
printf("%d %d %d %d\n", a, b, c, d);
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;
}
只运用循环结构编写一个输入4个整数从小到大顺序输出的c++程序
下面是一个使用循环结构编写的输入4个整数从小到大顺序输出的C++程序示例:
```cpp
#include <iostream>
using namespace std;
int main() {
int num[4];
// 输入4个整数
cout << "请输入4个整数:" << endl;
for (int i = 0; i < 4; i++) {
cout << "整数" << i+1 << ":";
cin >> num[i];
}
// 使用冒泡排序将整数从小到大排序
for (int i = 0; i < 4 - 1; i++) {
for (int j = 0; j < 4 - i - 1; j++) {
if (num[j] > num[j+1]) {
int temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
// 输出排序后的整数
cout << "从小到大顺序输出的整数为:";
for (int i = 0; i < 4; i++) {
cout << num[i] << " ";
}
cout << endl;
return 0;
}
```
在这个程序中,我们首先定义了一个大小为4的整型数组 `num` 来存储输入的四个整数。
然后,使用循环结构和 `cin` 语句,依次获取用户输入的四个整数,并将它们存储在数组 `num` 中。
接下来,我们使用冒泡排序算法对数组 `num` 进行排序,将整数从小到大排列。冒泡排序算法会多次遍历数组,每次比较相邻的两个元素,如果它们的顺序不对,则交换它们的位置,直到整个数组排好序。
最后,使用循环结构和 `cout` 语句,依次输出排序后的整数。
希望这个示例对你有帮助!如果还有其他问题,请随时提问。
相关推荐
![](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)