dimanche 8 avril 2018

Random array gives invalid output after first element [C]

I'm making a simple program that functions as a hot/cold guessing game with a randomly generated number (enter a guess, tells you higher or lower, repeats until correct number is guessed.) I've had some obstacles with random number generation, and the best solution I could create is generating an array of 1000 random numbers.

The first time playing through the game uses the first random number generated by the array, however, any time after the first game uses 4040 as the random number, regardless of the range of possible random numbers (should be 1-100 for the normal difficulty setting). I have tried to diagnose the problem in multiple ways, but I believe this problem is too difficult to solve with the very little experience I have with programming (I'm still in the process of taking my first programming course), so any help with identifying the problem would be greatly appreciated.

Relevant parts of the code:

int main()
{
    int randomArray[1000];
    int randomNum;
    int e=0; //element of each array
    int input, score;
    time_t t;
    char level='n', mode;

    //srand ( time(NULL) );
    srand((unsigned) time(&t));

    do
    {
        game();
    }
    while(level!='!');

    return 0;
}

void game()
{
    int randomArray[1000];
    int randomNum;
    int input;
    char level;

    printf("Chose difficulty (? for help, ! to quit): \n");
    printf("Normal (N)\n");
    printf("Medium (M)\n");
    printf("Hard (H)\n");
    printf("Impossible (I)\n");
    scanf("%c", &level);

    if(level=='N' || level=='n')
    {
        randomNum=rngNormal();
    }
    if(level=='M' || level=='m')
    {
        randomNum=rngMedium();
    }
    if(level=='H' || level=='h')
    {
        randomNum=rngHard();
    }
    if(level=='I' || level=='i')
    {
        randomNum=rngImpossible();
    }
    if(level=='?')
    {
        printf("Normal: generates random number from 1-100\nMedium: generates random number from 1-500\n");
        printf("Hard generates random number from 1-1,000\nImpossible: generates random number from 1-32,767");
    }

    getche();
    system("cls");
    printf("RANDOM NUMBER: %d\n", randomNum);//added for testing purposes
    input=load();
    while(input!=randomNum)
    {
        compare(input, randomNum);
        input=load();
     }
     compare(input, randomNum);

    return 0;
}

int rngNormal()
{
    int randomArray[1000];
    int randomNum;
    time_t t;
    int e=0;

    //generates random array
    if(e==0)
    {
        for(int a=0; a<1000; a++)
        {
            randomArray[a]=rand()%100+1;
        }

        for(int x=0; x<1000; x++)//added for testing purposes
        {
            printf("%3d ", randomArray[x]);
        }
    }

    randomNum=randomArray[e];

    e++;

    return randomNum;
}




Aucun commentaire:

Enregistrer un commentaire