对于这个程序,我们必须创建一个用户定义的函数来返回 60-100 值之间的 25 个随机变量,但是当我运行该程序时,所有 25 个值都是相同的。我在编程方面很新,我认为错误存在于定义用户函数的地方,因为我认为与其运行变量 25 次,不如它只运行一次并打印第一个值 25 次。但我不知道如何真正修复它:(
#include <stdlib.h>
#include <time.h>
int get_value (int Random);
int main ()
{
srand(time(NULL));//to randomize the number after each run
int Random = rand()%40+60;
printf("These are the temperatures for the day\n");
int temp[25], i;
for (i=0; i<25; i++)
{
temp[i] = Random;
printf("%d\n" ,temp[i]);
}
return 0;
}
int get_value (int Random)
{
Random = rand() % 40 + 60;
}
最佳答案
那是因为 get_value()
没有返回任何东西。 Random
参数是您(可能)传递的 Random
的副本。覆盖(非常量)函数参数是合法的,但它不会找到调用者的方式。第二个问题是你永远不会调用这个函数,你只是重复你生成的第一个随机数。
我建议你像这样重写函数
int get_value (void)
{
return rand()%41+60; // range 60 to 100
}
然后这样调用它
temp[i] = get_value();
关于c - C输出中随机数生成器的用户定义函数不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33200859/