使用冒泡法排序,将12个浮点数按照从小到大的顺序放在数组中
时间: 2024-02-24 10:00:45 浏览: 29
好的,以下是冒泡排序的C++代码实现:
```cpp
#include <iostream>
using namespace std;
void bubbleSort(float arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
float temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
float arr[12] = { 6.7, 3.2, 8.9, 1.5, 4.6, 2.3, 7.8, 9.0, 5.4, 0.1, 2.5, 3.9 };
int n = 12;
bubbleSort(arr, n);
cout << "排序后的数组为:" << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
以上代码将12个浮点数按照从小到大的顺序放在了数组中,你可以根据自己的需要进行修改使用。
相关问题
用C语言用冒泡法排序,对12个浮点数,这12个浮点数放在数组。从小到大
下面是用C语言实现的冒泡排序算法,对12个浮点数从小到大排序:
```c
#include <stdio.h>
int main() {
float nums[12] = {5.6, 4.3, 2.1, 9.5, 8.0, 1.2, 3.7, 6.4, 7.9, 0.5, 11.2, 10.0};
int i, j;
float temp;
// 冒泡排序
for (i = 0; i < 11; i++) {
for (j = 0; j < 11 - i; j++) {
if (nums[j] > nums[j + 1]) {
temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
// 输出排序后的结果
printf("排序后的结果为:");
for (i = 0; i < 12; i++) {
printf("%.1f ", nums[i]);
}
return 0;
}
```
输出结果如下:
```
排序后的结果为:0.5 1.2 2.1 3.7 4.3 5.6 6.4 7.9 8.0 9.5 10.0 11.2
```
用c语言用冒泡法排序,对12个浮点数,这12个浮点数放在数组。从小到大
好的,这是一个常见的冒泡排序问题,我可以为您提供一个示例代码:
```c
#include <stdio.h>
int main()
{
float arr[12] = {2.3, 4.5, 1.2, 3.4, 5.6, 6.7, 8.9, 9.0, 7.8, 0.1, 10.2, 11.3};
int i, j;
float temp;
// 冒泡排序
for (i = 0; i < 11; i++) {
for (j = 0; j < 11 - i; j++) {
if (arr[j] > arr[j + 1]) {
// 交换两个数的位置
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// 输出排序后的结果
printf("排序后的结果:\n");
for (i = 0; i < 12; i++) {
printf("%.2f ", arr[i]);
}
printf("\n");
return 0;
}
```
在这个代码中,我们首先定义了一个包含12个浮点数的数组`arr`,然后使用两个嵌套的`for`循环来实现冒泡排序。在内层循环中,我们比较相邻的两个数的大小,如果前一个数比后一个数大,就交换它们的位置。这样,每一轮循环都会将当前数组中最大的数移到最后面。
最后,我们输出排好序的结果。注意,这里使用了`printf`函数的格式化输出来保证输出结果只保留小数点后两位。
相关推荐
![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)