#include <Stdafx.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <math.h>
using namespace std;
int rand_0toN1(int n);
int hits[10];
int main()
{
int n;
int i;
int r;
srand( static_cast<unsigned int>(time(NULL))); // set seed for random numbers
cout<< "Enter number of trials to run ";
cout<< "and press ENTER: ";
cin>> n;
// run n trials. for each trial, get a number from 0 to 9 and then
// increment the corresponding element in the hits array
for(i = 1; i <= n; i++)
{
r = rand_0toN1(10);
hits[r]++;
}
// print all the elements in the hits array, along with the ratio
// of hits to the EXPECTED hits (n / 10)
for(i = 0; i < 10; i++)
{
cout<< i << ": " << hits[i] << " Accuracy: ";
cout<< static_cast<double>(hits[i]) / (n / 10)
<< endl;
}
system("pause");
return 0;
}
// random 0-to-N1 function
// generate a random integer from 0 to N - 1
int rand_0toN1(int n)
{
return rand() % n;
}
I'M having a little trouble understanding the program above. The function rand_0toN1 returns rand() % n, in this case I believe that it's returning a random number from 1-10 because 10 was passed as an argument through n, which is not the same n that was declared at the beggining of the program but local to the function only. DId I get that part right.
Secondly was going on with these two lines?
hits[r]++;
&
cout<< static_cast<double>(hits[i]) / (n / 10)
Thanks.