我一直在尝试编写一个小型 C 函数来生成随机值。问题是每次在 for 循环中调用该函数时它都会返回相同的值。我知道问题是 srand 的种子为 NULL。我想知道的是如何纠正它,以便在 for 循环的每次迭代中函数返回不同的值。代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int randInt(int,int);
void main(){
int min=100, max=200,i=0;
for(i;i<11;i++){ printf("%d \n",randInt(min,max)); }
}
int randInt(int a,int b){
srand(time(NULL));
int randValue;
randValue=1+(int)rand()%(b-a+1);
return randValue;
}
如果您有解决方案或可以发布一些解决方案的引用,请告诉我。预先感谢您!
编辑:遇到问题#2,将 srand(time(NULL)) 替换为 main 后,每次迭代现在都会生成低于我范围的数字,即最初我想要 100 到 200 之间的数字,但它也包括 0 到 0 之间的数字100. 这个问题已通过 randValue=a+(int)rand()%(b-a+1);
解决正如评论中所建议的
最佳答案
将 srand(time(NULL));
放在 main
中,紧接在 {
要生成 100-200 范围内的随机数,请添加 100 或 a
,而不是加 1
randValue=(int)rand()%(b-a+1);
所以它看起来像:
randValue=(int)rand()%(b-a+1)+100;
关于c - 如何让随机值函数每次返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25822373/