我怎样才能生成0到1之间的随机数列表,但是它们的平均值为0.8?
我用C编写了这个小脚本,它会告诉你输出的数字是多少.这个问题并不是真正的C相关.
#include
#include
#include
int main(int argCount, char** argVector) {
std::cout << "Generating Randoms" << std::endl;
float avarage = 0.F;
srand(rand() + (int) time(NULL));
float ceiling = 0;
float bottom = 1;
for(unsigned int i = 0; i < 1000000; i++) {
float random = (float) (rand() % 101) / 100;
if(random > ceiling)
ceiling = random;
else if(random < bottom)
bottom = random;
avarage += random;
}
std::cout << "Avarage: " << avarage/1000000 << std::endl;
std::cout << "Ceiling: " << ceiling << std::endl;
std::cout << "Bottom: " << bottom << std::endl;
return 0;
}
这输出:
Generating Randoms
Avarage: 0.499287
Ceiling: 1
Bottom: 0
我希望天花板和底部仍然是0和1,但能够改变平均值.该算法最好也应该是有效的.
我再次发布C代码,但任何语言都可以.