【发布时间】:2011-10-17 08:46:17
【问题描述】:
我正在玩弄数组,填充伪随机数,查找最小值和最大值以及它们的索引和出现次数,我注意到一些奇怪的东西 - 当使用 srand 种子时,最小值和最大值的数量出现次数总是相等的。这对我来说似乎不是很随机。
是否有另一种方法来获得不同数量的最小值和最大值出现,就像人们对随机数所期望的那样?
这是我的代码(我正在学习,所以它可能是混乱和低效的,欢迎提出建议)
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;
void findExtremes( const int[], int);
int main()
{
const int lenght = 2000; //define lenght
int array1[lenght];
srand(time(0));
for ( int i = 0; i < lenght; i++) //populate array with random numbers and print them out
{
array1[i] = rand() % 3000;
cout << "Index " << i << " = " << array1[i] << endl;
}
findExtremes(array1, lenght); // call fn
return 0;
}
void findExtremes( const int array[], int size)
{
int maxV, minV, maxI, minI;
maxV = array[0];
minV = array[0];
minI = 0;
maxI = 0;
for ( int i = 1; i < size; i++)
{
if ( array[i] > maxV)
{
maxV = array[i];
maxI = i;
}
if ( array[i] < minV)
{
minV = array[i];
minI = i;
}
}
//find the number of occurances for min and max values
int minOcc = 0;
int maxOcc = 0;
for ( int i = 1; i < size; i++)
{
if (array[i] == minV)
minOcc++;
if (array[i] == minV)
maxOcc++;
}
//output
cout << "\nMinmim value is index " << minI << " with value " << minV << " and " << minOcc << " occurances" << endl;
cout << "\nMaxium value is index " << maxI << " with value " << maxV << " and " << maxOcc << " occurances" << endl << "\n";
}
【问题讨论】:
-
rand() 基于伪随机函数。所以很有可能它不会那么随机。如果您需要强随机值,则需要搜索密码随机数生成器,因为大多数加密算法都是基于非常强的生成器
-
您正在与 minV 比较两次(发现出现时)
-
谢谢 DeyyyFF,我完全相信自己。请关闭问题。我感到愚蠢和羞愧:) 懒惰的复制和粘贴显然是不好的做法......
-
我认为这个问题不应该结束。关于随机数生成和播种,大多数答案都是错误的。这个问题仍然有价值,因为很多人都陷入了同样的陷阱。