c++ - 随机 0 出现在 C++ 数组中
问题描述
我正在为学校创建一个冒泡排序程序。问题是当我将结果输出给用户时,数组中有随机的 float 0 值,我不知道它们为什么在那里。提前感谢您的帮助。
代码:
#include <iostream>
#include <string>
using namespace std;
float* bubble_sort(float* numbers){
bool changes;
float temp;
while(true){
changes=false;
//Loop through the array
for(int i=0; i<sizeof(numbers); i++){
//Compare the pair
if(numbers[i]>numbers[i+1]){
//Swap if the one on the left is larger
temp=numbers[i];
numbers[i]=numbers[i+1];
numbers[i+1]=temp;
}
}
//If there hasn't been any changes
//break
if(changes==false){break;}
}
//Return the numbers
return numbers;
}
int main(){
while(true){
try{
//Get the amount of numbers in the array
int amount;
cout<<"How many numbers are in the array ";
cin>>amount;
//Setup the array
float numbers[amount];
cout<<endl;
//Get the numbers and add to the array
for(int i=0; i<amount; i++){
cout<<"Enter a number to add to the list ";
cin>>numbers[i];
}
//Bubble sort the numbers
float* result_numbers=bubble_sort(numbers);
//Format the resulting array for printing
string result("[");
for(int i=0; i<sizeof(numbers); i++){
result=result+to_string(numbers[i])+", ";
}
result.append("]");
//Output the result
cout<<"The bubble sorted array is: "<<result<<endl;
break;
}catch(...){
//Print an error if they don't enter a number
cerr<<"You must enter a number"<<endl;
}
}
return 0;
}
然后,当我使用以下数字运行代码时:4、3、2、1。我得到了输出
气泡排序的阵列为:[3.000000,2.000000,1.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,4.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,2.000000,2.000000,2.000000,2.000000,2rand
解决方案
推荐阅读
- c - 桶排序算法
- c - fork 线程安全吗?
- python - 在 jinja 的嵌套对象中选择定义的属性
- minecraft - 如何在 1.12.2 中 /fill with Armor Stand
- database - pg_cron 扩展连接失败
- node.js - 有没有一种有效的方法来获得成员 discord.js 的最稀有角色
- python - 如何解决 heroku flask 应用程序上的应用程序错误?
- visual-studio - 如何从 Visual Studio 将参数传递给 MSBuild?
- android - 适用于 Android 11 目标的离线提醒通知应用程序(Google Keep 之类)。应用关闭时如何接收通知?
- c# - 在asp.net中将大量数据从视图发送到控制器