要求读入若干整数(最少1个不超过4个),然后按从小到大的顺序输出
时间: 2024-06-13 15:06:10 浏览: 10
以下是Python实现读入若干整数并按从小到大顺序输出的代码:
```python
nums = input().split() # 读入若干整数并以空格分隔
nums = list(map(int, nums)) # 将输入的字符串转换为整数列表
nums = list(set(nums)) # 去重
nums.sort() # 排序
for num in nums:
print(num, end=' ')
```
相关问题
要求读入若干整数(最少1个不超过4个),然后按从小到大的顺序输出 C语言
以下是C语言读入若干整数并按从小到大顺序输出的代码示例:
```c
#include <stdio.h>
int main() {
int n, i, j, temp, arr[4];
printf("请输入1-4个整数,用空格隔开:\n");
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("从小到大的顺序输出为:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
c语言 读入若干整数,最少一个,最多四个,从小到大排序
以下是一个示例代码:
```c
#include <stdio.h>
void sort(int arr[], int len) {
int i, j, temp;
for (i = 0; i < len - 1; i++) {
for (j = i + 1; j < len; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int main() {
int n[4], i, count = 0;
// 读入整数,最多四个
for (i = 0; i < 4; i++) {
if (scanf("%d", &n[i]) == 1) {
count++;
} else {
break;
}
}
// 排序
sort(n, count);
// 输出
for (i = 0; i < count; i++) {
printf("%d ", n[i]);
}
printf("\n");
return 0;
}
```
这段代码中,我们首先定义了一个 `sort` 函数,它用来对数组进行排序,这里采用的是冒泡排序。然后在 `main` 函数中,我们定义了一个长度为 4 的整型数组 `n` 来存储输入的整数,然后用一个循环读入这些整数,同时记录输入的个数 `count`,最多读入 4 个整数。接着调用 `sort` 函数对数组进行排序,最后输出排序后的结果。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)