mercredi 16 février 2022

I use rand() but my values are same. Why? [duplicate]

I am a begginer in C and I am watching Thenewboston's tutorial. I just watched the tutorial number 38 and learnt about rand(). So there was a challenge in this video. The challenge is:

Make a program which represents a dice game. In the game there are 3 dices that roll. The dices are rolled and the user has to guess if the next roll will be bigger, lower or the same.

My code generally works(says right if the values are bigger smaller or same or even if the input is invalid) but I always get the same exact numbers for the first roll (17) and the second roll (16) (I have putted a printf that prints the value of the second roll. That's how I know)

What is wrong with my code? Have I implemented something wrong in rand()?

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>

// rolls dice 3 times
// ask user if next rolls will be bigger
// print if user was right
int main()
{
    int Diceroll1;
    int First_roll = 0;
    int Diceroll2;
    int Second_roll = 0;
    int i;
    char higher_same_lower;

    for(i = 0; i < 3; i++){
        Diceroll1 = (rand()%6) + 1;
        First_roll += Diceroll1;
    }

    printf("welcome to Dice roll! Let's start the game...\n");

    printf("The sum of the dice roll is %d\n", First_roll);
    printf("Is the next dice roll going to be bigger, lower or the same than this one? Press b, l and s respectively ");

    scanf("%c", &higher_same_lower);

    for(i = 0; i < 3; i++){
        Diceroll2 = (rand()%6) + 1;
        Second_roll += Diceroll2;
    }

    printf("%d ", Second_roll);
    if(isalpha(higher_same_lower)){
            if(higher_same_lower == 'b' && Second_roll > First_roll){
                printf("Congrats you are right!");
            }
            else if(higher_same_lower == 'b' && Second_roll < First_roll){
                printf("We are sorry you are wrong!");
            }
            else if(higher_same_lower == 'l' && Second_roll < First_roll){
                printf("Congrats you are right!");
            }
            else if(higher_same_lower == 'l' && Second_roll > First_roll){
                printf("We are sorry you are wrong!");
            }
            else if(higher_same_lower == 's' && Second_roll == First_roll){
                printf("Congrats you are right!");
            }
            else if(higher_same_lower == 's' && Second_roll != First_roll){
                printf("We are sorry you are wrong!");
            }
            else{
                printf("Invalid input. Please restart the game");
            }

    }
    else{
        printf("Invalid input. Please restart the game");
    }

}

Thanks in advance




Aucun commentaire:

Enregistrer un commentaire