I made this dice simulator which basically throws the dice 1 million times and outputs the frequency and percentage average for each side (1 to 6).
Everything is working fine, except my averages (floats) seem to be rounding up, causing 4% being "unassigned" at the end of the million rolls. I'm outputting with a setprecision of 2, but I only get 0's and no fractional numbers.
I was able to get a result of 16.67% after correcting an int to float conversion issue. I'm troubled a little bit by the fact that my program seems more accurate than my teacher's example, which has results ranging from 16.50% to 16.90%. Could it be that my randomization is flawed or that mine is in fact more truly random ?
for(Nb = 1; Nb >= 1 && Nb <= 1000000; Nb++)
{
// Calcul
srand(time(NULL) + Nb);
Face = rand() % 6 + 1;
switch(Face)
{
case 1: Fq1++;
break;
case 2: Fq2++;
break;
case 3: Fq3++;
break;
case 4: Fq4++;
break;
case 5: Fq5++;
break;
case 6: Fq6++;
break;
}
float Pour1 = Fq1 * 100 / Nb;
float Pour2 = Fq2 * 100 / Nb;
float Pour3 = Fq3 * 100 / Nb;
float Pour4 = Fq4 * 100 / Nb;
float Pour5 = Fq5 * 100 / Nb;
float Pour6 = Fq6 * 100 / Nb;
// Affichage
if(Nb % Mod == 0)
{
gotoxy(0,1);
cout << "Essaie avec " << Nb << " lancer(s):";
cout << endl << endl;
cout << setw(L1) << right << "Face";
cout << setw(L2) << right << "Fr\x82quence";
cout << setw(L3) << right << "Pourcentage";
cout << endl;
cout << setw(L1) << right << "1";
cout << setw(L2) << right << Fq1;
cout << fixed << setprecision(2) << setw(L3) << right << Pour1 << "%";
cout << endl;
cout << setw(L1) << right << "2";
cout << setw(L2) << right << Fq2;
cout << setw(L3) << right << Pour2 << "%";
cout << endl;
cout << setw(L1) << right << "3";
cout << setw(L2) << right << Fq3;
cout << setw(L3) << right << Pour3 << "%";
cout << endl;
cout << setw(L1) << right << "4";
cout << setw(L2) << right << Fq4;
cout << setw(L3) << right << Pour4 << "%";
cout << endl;
cout << setw(L1) << right << "5";
cout << setw(L2) << right << Fq5;
cout << setw(L3) << right << Pour5 << "%";
cout << endl;
cout << setw(L1) << right << "6";
cout << setw(L2) << right << Fq6;
cout << setw(L3) << right << Pour6 << "%";
cout << endl << endl;
if(Nb == 1000000)
{
cout << "Popup \x85 venir.";
_getch();
}
else
{
Mod = Mod * 10;
string Cont = "Presser une touche pour continuer.";
Centre = Cont.size();
cout << setw((80 - Centre) / 2) <<"" << Cont;
_getch();
clrscr();
}
}
}
}
Do not evaluate the last if, it is unfinished and will only be useful to output a goodbye message once the program has successfully shown the results for 1, 10, 100, 1000, 10000, 100000, 1000000 rolls (every power of 10, up to 1 million).
you should use rand() once before each call to it because the first answer is flawed, like you you should use it once just after your call to srand(), and your function would produce better results!