我正在为我的 C 类制作游戏(实际上是重新制作游戏),并且我有一个生成随机价格的函数。问题是我需要在整个游戏中调用此函数 60 次,并且每次调用该函数时都会重新生成新的数字。是否可以在不结束程序的情况下执行此操作,如果可以,那么怎么做?
到目前为止,我已经为该函数编写了一个 for 循环。但它只是将相同的函数打印了 60 次,而这正是我所期望的。
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int Prices(void)
{
//Random price generator
int Acid = rand() % 10+ 1;
int Coke = rand() % 150+ 101;
int Crack = rand() % 30 + 15;
int Ecstasy = rand() % 8 + 1;
int Herion = rand() % 100 + 46;
int Meth = rand() % 100 + 26;
int Opium = rand() % 65 + 31;
int Pills = rand() % 7 + 1;
int Shrooms = rand() % 30 + 16;
int Speed = rand() % 45 + 11;
int Weed = rand() % 20 + 21;
//Prints the above random prices to the main screen
printf("PRICE PER UNIT:\n\n");
printf("Acid: ""%i\n",Acid);
printf("Coke: ""%i\n",Coke);
printf("Crack: ""%i\n",Crack);
printf("Ecstasy: ""%i\n",Ecstasy);
printf("Herion: ""%i\n",Herion);
printf("Meth: ""%i\n",Meth);
printf("Opium ""%i\n",Opium);
printf("Pills: ""%i\n", Pills);
printf("Shrooms: ""%i\n", Shrooms);
printf("Speed: ""%i\n",Speed);
printf("Weed: ""%i\n",Weed);
printf("********************************************************************************\n");
return Acid && Coke && Crack && Ecstasy && Herion && Meth && Opium && Pills && Shrooms && Speed && Weed;
}
int main(void){
int Prices(void);
int i;
for(i=0; i<60; i++){
Prices();
}
}
好的,所以我删除了 srand 函数并且它起作用了,但我还需要一种方法来限制此函数在整个游戏中仅定期调用 60 次,而不是一次调用所有。
最佳答案
不要自己调用srand
,删除这一行:
srand((unsigned)time(NULL)); //Uses time as seed for random numbers
您的 time()
调用只有一秒的分辨率,每次循环运行所花费的时间远少于一秒,结果是您使用相同的值为随机数生成器播种每次都会产生相同的一组随机数字。
现代 rand()
实现负责自己为随机数生成器设置种子。
大多数随机数生成器实际上是其种子的确定性函数,您的 rand()
看起来就是其中之一。 standard指的是 rand()
生成的伪随机整数是有充分理由的。
关于objective-c - 我如何多次调用一个函数,每次调用它时都会改变函数内部的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5691387/