2

I am making a game for my C class (actually remaking one) and I have a function that produces random prices. The problem is that I need to call this function 60 times throughout the game and have the numbers regenerate to new ones every time the function is called. Is it possible to do this without ending the the program, and if so then how?

So far I've written a for loop for the funct. but it just prints the same function 60 times which I kindof expected to happen.

Here is the code:

#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();
    }
}

Ok So I deleted the srand function and that worked but I also need way to limit this function to being called only 60 times periodically throughout the game and not all at once.

4

2 回答 2

2

不要打电话给srand自己,删除这一行:

srand((unsigned)time(NULL)); //Uses time as seed for random numbers

您的time()调用只有一秒的分辨率,每次循环运行所需的时间远少于一秒,结果是您每次都使用相同的值播种随机数生成器,并产生相同的随机数集。

现代rand()实现负责自己播种随机数生成器。

大多数随机数生成器实际上是其种子的确定性函数,您rand()看起来就是其中之一。该标准指的是rand()出于充分的理由生成伪随机整数的内容。

于 2011-04-17T04:09:26.880 回答
0

一种选择是使用静态变量来指示您的种子是否已设置。这个片段将展示如何做到这一点:

...
static int srand_flag = 0;
if (!srand_flag) {
  srand_flag = 1;
  srand((unsigned)time(NULL));
}
...

这将确保您只调用一次种子,因此您不会遇到大多数time()实现为您提供的 1 秒粒度。

另一种选择是使用(通常是特定于平台的)毫秒计时器来代替您的种子。然而,什么函数调用给你的是高度依赖于平台的。在 Linux 中,您必须处理诸如此类的事情,clock_gettime()而在 Windows 中,您可能会处理诸如GetTickCount().

如果您绝对必须srand()每次都调用,最后一个选择是在每次调用之前延迟一秒钟,srand()以确保每次调用的计数器值都不同。 (这不是一个好的选择。)

于 2011-04-17T04:23:42.997 回答