supersaidso
supersaidso

Reputation: 69

rand() not giving values within numbers specified (in C)

I just want it to give me values between 1 and 6, but it's giving me this instead:

P1d1 = 1445768086

P1d2 = -2

P2d1 = 1982468450

P2d2 = 198281572

Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (){

srand(time(NULL));

/*Player 1*/

int P1d1 = 1 + rand() % 6;  //Rolls Player 1's first die; random # between 1-6
int P1d2 = 1+ rand() % 6;  //Rolls Player 1's second die; random # between 1-6
int P1total = P1d1 + P1d2;  //Takes total of both rolls

/*Player 2*/

int P2d1 = 1 + rand() % 6; //Rolls Player 2's first die; random # between 1-6
int P2d2 = 1 + rand() % 6; //Rolls Player 2's second die; random # between 1-6
int P2total = P2d1 + P2d2; //Takes total of both rolls

printf("P1d1 = %d\nP1d2 = %d\nP2d1 = %d\n P2d2 = %d\n");

}

I'm not allowed to use functions as we have not covered them in class yet. Any help is very much appreciated!

Upvotes: 0

Views: 99

Answers (1)

Chris Hayes
Chris Hayes

Reputation: 12030

Your printf has no variables specified. You are therefore getting random garbage printed, not the actual variable values you're looking for.

You should have this:

printf("P1d1 = %d\nP1d2 = %d\nP2d1 = %d\n P2d2 = %d\n", P1d1, P1d2, P2d1, P2d2);

Upvotes: 5

Related Questions