需要冒泡排序100个随机数,范围从-100到100,从高到低,同时保持当前的小数位精度。我有一个冒泡排序功能但不知道如何从另一个函数中调用它。
#include "stdafx.h"
#include <fstream> // writing data to disk
#include <cstdlib> // standard general utilities library "# generator"
#include <ctime> // convert time value to string
#include <iostream>
#include <iomanip> // set precision
using namespace std;
// Functions
void number_Generator();
void bubbleSort (double *array, double length)
{
int i,j;
for (i=0;i<100;i++)
{
for (j=0;j<i;j++)
{
if(array[i]>array[j])
{
int temp = array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
system("pause");
cout.precision (6);
number_Generator();
}
// Number Generator Function
void number_Generator()
{
double Final_Avg = 0;
double Random_Cap = 100;
double Samples_To_Create = 100;
srand((unsigned)time(0));
double rndDbl;
int rndInt;
double rndAvg = 0, rndMin = 0, rndMax = 0;
int counter = 0;
double temp = 0;
double dblRanAry[100];
Final_Avg = rndAvg / counter; // final average to display
double lDbl=0, hDbl=Random_Cap;
int lInt = 0, hInt=1;
double dblRange=(hDbl-lDbl)+1;
int intRange=(hInt-lInt)+1;
for(int index=0; index<Samples_To_Create; index++)
{
rndInt = lInt+int(intRange*rand()/(RAND_MAX + 1.0));
rndDbl = lDbl+double(dblRange*rand()/(RAND_MAX + 1.0));
// random number if statement
if (rndInt == 0){
rndDbl = -(rndDbl);
} //start of Min/Max if statements
if (rndMin == 0){
rndMin = rndDbl;
}
else if (rndDbl < rndMin){
rndMin = rndDbl;
}
if (rndMax == 0){
rndMax = rndDbl;
}
else if (rndDbl > rndMax){
rndMax = rndDbl;
} //end of Min Max if statements
temp = rndDbl;
rndAvg += temp;
dblRanAry[counter] = temp;
counter++;
cout.precision (6);
cout << fixed << " " << rndDbl << endl;
}
cout << " " << endl
<< "The average = " << fixed << rndAvg/counter << endl
<< " " << endl
<< "The Min = " << fixed << rndMin << endl
<< " " << endl
<< "The Max = " << fixed << rndMax << endl
<< " " << endl;
} // end of number generator function
答案 0 :(得分:1)
你需要做几件事:
添加sort函数调用,如下所示:
int _tmain(int argc, _TCHAR* argv[])
{
system("pause");
cout.precision (6);
int dblArray[100] = {0.0}; //these change are explained below
number_Generator(dblArray, 100); //100 means generate 100 random numbers
//remove double dblRanAry[100] inside the generator;
bubbleSort (dblArray, 100) ;
}
将number_Generator
的原型更改为
void number_Generator(double dblArray[], int length);
你的number_Generator
应该
您也可以更改number_Generator
以完成原型更改。
此外:
void bubbleSort (double *array, int length)
{ //^^array length is int, not double
for (int i = 0; i < length; i++)
{ //^^use length, not hardcoded 100
for (int j = 0; j < i; j++)
{
if(array[i] > array[j])
{
double temp = array[i];
//since array elements are double, not int
array[i] = array[j];
array[j] = temp;
}
}
}
}