I am making this code for a random dice roller and I want to get a random number until I get three 6's on the dice. For some reason this produces the same number for all runs, but on my for loop it works. Can I get some help getting this to work?
The pesky While loop in question:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int Ran(int max) {
return (rand() % max)+ 1;
}
int main(){
int max = 6;
int nsuc = 0, ncount = 0;
int matt = 40;
srand((unsigned) time(0));
for(int i = 1; i <= 20; i++){
while(!(nsuc >= 3)){
int nr = Ran(max);
if(nr < matt){
ncount++;
if(nr == 6){
nsuc++;
}
}
}
printf("Number of rolls until 3 6's = %d\n", ncount);
}
}
Cleaned up the for loop so it's easier to read now:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void Shuffle() {
srand((unsigned) time(NULL));
}
int Ran(int max) {
return (rand() % max)+ 1;
}
void binomial(int run, int max, int btrials, int *array, int scount){
for(int j = 1; j<=run; j++){
for (int i=1;i<=btrials;i++){
int r = Ran(max);
if(r == 6){
scount++;
}
printf("Trial %i, roll = %d\n",i , r);
}
array[j-1] = scount;
scount = 0;
printf("\nEnd of Run %d\n\n",j);
}
}
int main(){
int Runs;
printf("How many runs do you want to do? > ");
scanf("%d", &Runs);
printf("\n");
int bdist[20];
int distcount = 0;
int max = 6;
int btrials = 20;
int suc[Runs+1];
int scount = 0;
Shuffle();
binomial(Runs, max, btrials, suc, scount);
printf("All counts of succesful 6 rolls.\n");
/*
for(int z = 1; z<=Runs; z++){
printf("Run %d has %d 6's\n", z, suc[z-1]);
}
*/
for(int k = 0; k<=btrials; k++){
for(int j = 1; j<=Runs; j++){
if(suc[j-1] == k){
distcount++;
}
}
bdist[k] = distcount;
distcount = 0;
}
for(int t = 0; t<=btrials; t++){
printf("Number of runs with %d 6s = %d\n", t, bdist[t]);
}
return 0;
}