c++ 输入数字个数和数字并排序
时间: 2024-05-15 20:15:52 浏览: 12
以下是Python语言的实现:
```python
# 输入数字个数
n = int(input("请输入数字个数:"))
# 输入数字
nums = []
for i in range(n):
num = int(input("请输入数字:"))
nums.append(num)
# 排序
nums.sort()
# 输出结果
print("排序后的结果为:", nums)
```
示例输出:
```
请输入数字个数:5
请输入数字:3
请输入数字:1
请输入数字:5
请输入数字:2
请输入数字:4
排序后的结果为: [1, 2, 3, 4, 5]
```
相关问题
用c++ 写 输入数字个数和数字并排序
以下是使用C语言编写输入数字个数和数字并排序的示例代码:
```
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Sorting the array using bubble sort
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted array in ascending order:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
在此示例中,我们首先要求用户输入要排序的数字的数量。然后,我们使用scanf函数从用户输入中读取数字,并将它们存储在一个数组中。接下来,我们使用冒泡排序算法对数组进行排序。最后,我们打印已排序的数组。
用c++代码写 输入数字个数和数字并排序
以下是用C语言实现输入数字个数和数字并排序的代码:
```c
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("请输入数字个数:");
scanf("%d", &n);
int arr[n];
printf("请输入数字:");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// 冒泡排序
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("排序后的数字为:");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
代码解释:
1. 首先,我们使用 `scanf()` 函数从控制台读取数字个数 `n`。
2. 然后,我们定义一个长度为 `n` 的整型数组 `arr` 来存储输入的数字。
3. 接着,我们使用 `for` 循环读取 `n` 个数字,并将它们存储在数组 `arr` 中。
4. 我们使用冒泡排序算法对数组 `arr` 进行排序。冒泡排序算法的基本思想是不断比较相邻两个数的大小,如果前一个数大于后一个数,就交换它们的位置。经过一轮比较后,最大的数就会被排到最后面。重复这个过程,直到所有的数都被排好序为止。
5. 最后,我们使用 `for` 循环输出排序后的数字。