I am trying to create a Dice Roll game where the user can roll up to 6 dice at a time. I am attempting to accomplish this by integrating pointers into my code. I am getting an output, with the desired amount of rolls as given by the user, but the output is incorrect. It is printing a pattern instead of printing random numbers. Any help is appreciated.
How many dice would you like to roll?
user input: 4
output: 3 0 3 0
How many dice would you like to roll?
user input: 5
output: 4 0 4 0 4
#include <stdio.h>
#include <stdlib.h>
void tossDie(int []);
int main() {
int diceArray[6] = { 0 };
int num = 0;
int x;
do {
printf("\nHow many dice would you like to roll? Please enter here: ");
scanf_s("%d", &num);//user enters amount of dice they want to roll)
if (num < 1 || num > 6) {
printf("\n\nPlease enter a number between 1 and 6.\n\n");
}
} while (num < 1 || num > 6);
tossDie(diceArray);
//print dice roll numbers
for (x = 0; x < num; x ) {
printf("%d ", diceArray[x]);
}
return 0;
}
void tossDie(int numbers[]){
int randomNum;
int x;
srand(time(NULL));
randomNum = (rand() % 6) 1; //random # between 1 - 6
for (x = 0; x < 6; x ){
numbers[x] = randomNum;
x ;
}
};
CodePudding user response:
Move
srand(time(NULL));
tomain()
. Only needed once.Only call
x
only per loop, not twice, to assigned all 6 elements of the array.Move
randomNum = (rand() % 6) 1;
to insidefor
loop to get different values.Check return value of
scanf_s("%d", &num);
against 1, before usingnum
.
Tip: Use an auto-formatter to save time and improve code presentation.
Design: I'd expect tossDie(int numbers[])
to also receive a num
to indicate numbers[]
width.
CodePudding user response:
Before I answer, please note that I don't program in C, so there may be some language-specific things that I am missing.
In your tossDie() function, you set the value of randomNum once, but don't reassign it after that. Therefore, your output should return the same number for all values in the array, like such:
Input: 5
Output: 3 3 3 3 3
To fix that, you should put the variable declaration in the for loop (if you want to use a variable at all).
Additionally, you initialise the random variable every time you run the method. Instead, you should declare it once, in the main method.
Also, there's a little issue in this block of code:
for (x = 0; x < 6; x ){
numbers[x] = randomNum;
x ;
}
};
You increase x twice in here: both in the first line and the third line. Instead, you should delete the x in the third line and have just the x in the first line.
Let me know if you have further questions or if there are still problems.