【发布时间】:2015-11-06 07:54:49
【问题描述】:
这是我应该用来创建一个函数的公式,该函数将用随机双精度数填充一个数组
lower bound + ( random integer / (maximum possible random number / (upper bound - lower bound)))
下限为 0,上限为 100,最大值为 RAND_MAX
该函数是一个不带参数的 double ___() 函数
在我的一生中,我无法弄清楚如何让这个公式作为一个函数工作,或者如何用它的结果填充数组
它只是给了我错误:
无法将双精度 ()() 转换为双精度
我在这里有一个“某种”工作版本的程序
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
using namespace std;
int buildArray(double[]);
void printArray (double[],int, int);
double randDouble();
const int LOWER=0;
const int UPPER=100;
const int ARRAY_SIZE=100;
int main(){
int numberElements = 0;
int line;
double MainArray [ARRAY_SIZE];
numberElements=buildArray(MainArray);
cout<< "how many values per line? ";
cin>>line;
cout<<"unsorted Values"<<endl<<endl;
printArray(MainArray, numberElements, line);
cout<<endl<<"sorted values"<<endl<<endl;
sort(MainArray, MainArray + numberElements);
cout<<endl<<endl;
printArray(MainArray, numberElements, line);
return 0;
//the function would normally go right here
}
int buildArray(double MainArray[]){
int i=0;
int arrayTotal;
srand(time(NULL));
while(arrayTotal <20){
arrayTotal=rand()%100;
}
while(i<arrayTotal){
//and I would insert it below here instead of this jerry-rigged thing
MainArray[i]=rand()%100/((double)RAND_MAX/10000);
i++;
}
return arrayTotal;
}
void printArray(double MainArray[],int numOfValues,int line){
int lineBreak = 0;
for(int i = 0; i < numOfValues; i++){
if (lineBreak==line){
cout<<endl;
lineBreak=0;
}
lineBreak++;
cout<<setprecision(5)<<MainArray[i]<<" ";
}
}
抱歉,我的代码草率且效率低下。也很抱歉,这个问题可能很愚蠢,有一个明显的解决方案。我现在实际上并没有上任何课程,我只是想自学 C++,所以我没有其他人可以问。
【问题讨论】:
-
只调用一次
srand。你能写一个函数来做 1 个浮点数并以此为基础吗?