首页 > 解决方案 > 随机 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++

解决方案


推荐阅读