C rand()数组不';我不会每次运行代码时都更改
对于我正在运行的一个小程序,我使用rand()函数为23个整数的数组提供数字。我发现每次运行代码时,它都会重用数组中以前使用过的相同数字,因此每次迭代都不会得到不同的结果。我如何解决这个问题 编辑:代码是关于生日悖论的理论和实验。这一悖论表明,在一个满是23人的房间里,你与任何人共享生日的几率是50%,但大多数人自然会认为这一几率要小得多C rand()数组不';我不会每次运行代码时都更改,c,random,C,Random,对于我正在运行的一个小程序,我使用rand()函数为23个整数的数组提供数字。我发现每次运行代码时,它都会重用数组中以前使用过的相同数字,因此每次迭代都不会得到不同的结果。我如何解决这个问题 编辑:代码是关于生日悖论的理论和实验。这一悖论表明,在一个满是23人的房间里,你与任何人共享生日的几率是50%,但大多数人自然会认为这一几率要小得多 #include "stdio.h" #include "stdlib.h" #define interations 10 //number of repi
#include "stdio.h"
#include "stdlib.h"
#define interations 10 //number of repitition in the code for a more accurate percentage
#define numppl 23 //number of people
int main()
{
int inv;
float percent = 0, sum = 0;
int i, j, k;
int seq[numppl];
for (inv = 0; inv < interations; inv++)
{
for (i = 0; i < numppl; i++) {
seq[i] = rand() % 365; //creates a random array of 'numppl' integers every iteration
}
for (j = 0; j < numppl; j++)
{
for (k = j + 1; k < numppl; k++)
{
if (seq[j] == seq[k]) //if any two number in the array match each other, increment sum by 1
sum++;
}
}
}
percent = (sum / interations) * 100; //divide the amount of arrays with numbers that match with the number of total arrays generated for a percentage
printf("Chance of two people sharing the same birthday is %f percent", percent);
}
#包括“stdio.h”
#包括“stdlib.h”
#在代码中定义重复次数10//以获得更准确的百分比
#定义numppl 23//人数
int main()
{
国际投资部;
浮动百分比=0,总和=0;
int i,j,k;
整数序列[numppl];
对于(inv=0;inv
每次迭代都是一个不同的随机数数组,但当我再次运行代码时,数组与以前相同,因此我得到的百分比与
rand()
的预期行为相同。您需要使用srand()
为随机数生成器设定种子。您需要向我们展示您为此编写的代码。除非我们知道你做了什么,否则我们帮不了你。