0
#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(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_0_toN1(int n)
{
    return rand() % n;
}

in the program above I'M getting an error on the srand(time(NULL)); line. Something about tiime_t and an unsigned int. I'M typing it in just like the book shows as far as I can tell. Thanks for any help here.

3
Contributors
2
Replies
4
Views
4 Years
Discussion Span
Last Post by Sky Diploma
0

time_t isn't a compatible type with unsigned int, which srand() expects as an argument, so the implicit conversion fails. You can take the easy way out and cast the result of time() to unsigned int:

srand((unsigned)time(NULL));

However, be warned that this conversion technically isn't portable. But in practice, the chances of it failing are vanishingly small.

0
 srand( static_cast<unsigned int>( time( NULL ) ) );

Just to add up on the above point. Maybe its time for the static_cast to kick in and try a safe conversion :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.