I've been asked for an assignment to do the roll dice experiment multiple times and change number of dice rolls for each experiment. I'm trying to use a for
loop to avoid repeating the same code multiple times.
#include <iostream>
#include <cmath>
#include <time.h>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
// CONSTANTES
const short maxValue = 6;
const short minValue = 1;
srand(time(0));
// VARIABLES
int nbLancer;
int maxLancer = 1;
int frequence1 = 0;
int frequence2 = 0;
int frequence3 = 0;
int frequence4 = 0;
int frequence5 = 0;
int frequence6 = 0;
double pourcentage1;
double pourcentage2;
double pourcentage3;
double pourcentage4;
double pourcentage5;
double pourcentage6;
short dice;
short nbExperience;
// TRAITEMENTS
for (nbExperience = 0; nbExperience < 7; nbExperience )
{
for (nbLancer = 0; nbLancer < maxLancer; nbLancer )
{
dice = (rand() % (maxValue - minValue 1) minValue);
switch (dice)
{
case 1:
frequence1 ;
break;
case 2:
frequence2 ;
break;
case 3:
frequence3 ;
break;
case 4:
frequence4 ;
break;
case 5:
frequence5 ;
break;
case 6:
frequence6 ;
break;
}
}
cout << frequence1 << ", " << frequence2 << ", " << frequence3 << ", " << frequence4 << ", " << frequence5 << ", " << frequence6 << endl;
pourcentage1 = (frequence1 * 100) / nbLancer;
pourcentage2 = (frequence2 * 100) / nbLancer;
pourcentage3 = (frequence3 * 100) / nbLancer;
pourcentage4 = (frequence4 * 100) / nbLancer;
pourcentage5 = (frequence5 * 100) / nbLancer;
pourcentage6 = (frequence6 * 100) / nbLancer;
cout << fixed << setprecision(2) << pourcentage1 << "%, " << pourcentage2 << "%, " << pourcentage3 << "%, " << pourcentage4 << "%, " << pourcentage5 << "%, " << pourcentage6 << "%" << endl;
_getch();
// RESET
frequence1 = 0;
frequence2 = 0;
frequence3 = 0;
frequence4 = 0;
frequence5 = 0;
frequence6 = 0;
}
}
How do I multiply the value of the variable maxValue
that's inside the second for
loop? The desired result would be to multiply the value of the variable by 10 every time the first loop breaks.
CodePudding user response:
Well, first of all, if you want to change its value, maxValue
can't be const
.
short maxValue = 6;
const short minValue = 1;
However, what it appears you really want is, is a third loop.
for (maxValue = 6; maxValue < 6000; maxValue *= 10)
{
for (nbExperience = 0; nbExperience < 7; nbExperience )
CodePudding user response:
The solution was actually quite simple. After trying multiple things, I found out I only needed to add (maxLancer *= 10) to the first for loop in that manner:
for (nbExperience = 0; nbExperience < 7; nbExperience , (maxLancer *= 10))