c++让输入数字排序
时间: 2023-08-03 11:21:20 浏览: 54
您好!要让输入的数字排序,可以使用冒泡排序或快速排序等算法。以下是冒泡排序的示例代码:
```c++
#include <iostream>
using namespace std;
int main() {
int n, temp;
cout << "请输入数字个数:";
cin >> n;
int nums[n];
cout << "请输入数字:";
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
// 冒泡排序
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (nums[j] > nums[j+1]) {
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
cout << "排序后的数字为:";
for (int i = 0; i < n; i++) {
cout << nums[i] << " ";
}
return 0;
}
```
希望能对您有所帮助!
相关问题
c++ 输入数字个数和数字并排序
以下是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函数从用户输入中读取数字,并将它们存储在一个数组中。接下来,我们使用冒泡排序算法对数组进行排序。最后,我们打印已排序的数组。