Search code examples
objective-ccsrand

How would I call a function several times changing the random numbers inside the function every time it is called?


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.


Solution

  • Don't call srand yourself, delete this line:

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

    Your time() call only has one second resolution and each run through the loop takes much much less than one second, the result is that you're seeding the random number generator with the same value every time and that yields the same set of random numbers.

    Modern rand() implementations take care of seeding the random number generator themselves.

    Most random number generators are actually deterministic functions of their seed, your rand() looks like it is one of these. The standard refers to what rand() generates as pseudo-random integers for a good reason.