Here is the randint function to use: //randint.cpp #include \"randint.h\" #inclu
ID: 3543451 • Letter: H
Question
Here is the randint function to use: //randint.cpp #include "randint.h" #include <chrono> using namespace std::chrono; //linear congruential pseudorandom number generator int randint(){ //use the clock for an initial pseudorandom number static long x = time_point_cast<microseconds>( system_clock::now()).time_since_epoch().count(); //calculate the next pseudorandom number x = (1103515245 * x + 12345) & 0x7fffffff; //parameters from glibc(?) return x; } Put this code in a file named randint.cpp, and also write the matching header file randint.h. Write a main named filename.cpp which calls randint 1000 times and counts how many times the last digit (in decimal) is a 0, a 1, etc. The output might look like this: There were 99 0's. There were 103 1's. There were 90 2's. and so on (if randint is really pretty random, all the counts will be close to 100), or the counts might be all over the place if it is not very random. To compileL
g++-4.7 -std=c++11 filename.cpp randint.cpp
Explanation / Answer
//randint.h
#ifndef RANDINT_H
#define RANDINT_H
int randint();
#endif
//randint.cpp
#include "randint.h"
#include <chrono>
using namespace std::chrono;
//linear congruential pseudorandom number generator
int randint(){
//use the clock for an initial pseudorandom number
static long x = time_point_cast<microseconds>(
system_clock::now()).time_since_epoch().count();
//calculate the next pseudorandom number
x = (1103515245 * x + 12345) & 0x7fffffff; //parameters from glibc(?)
return x;
}
//filename.cpp
#include <iostream>
#include "randint.h"
using std::cout;
int main()
{
int digitCount[10] = {};
for (int i = 0; i < 1000; ++i)
++digitCount[randint() % 10];
for (int i = 0; i < 10; ++i)
cout << "There were " << digitCount[i] << " " << i << "'s ";
}