The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
![]() |
Home ![]() ![]() |
||
![]() ![]() ![]() ![]() ![]() ![]() |
||
Checking the Other Values
howMany only counts the occurrences of a particular value, and we are interested in seeing how many times each value appears. We can solve that problem with a loop: int numValues = 20;int upperBound = 10; pvector<int> vector = randomVector (numValues, upperBound); cout << "value\thowMany"; for (int i = 0; i<upperBound; i++) { cout << i << '\t' << howMany (vector, i) << endl; }
This code uses the loop variable as an argument to howMany, in order to check each value between 0 and 9, in order. The result is: value howMany0 2 1 1 2 3 3 3 4 0 5 2 6 5 7 2 8 0 9 2 Again, it is hard to tell if the digits are really appearing equally often. If we increase numValues to 100,000 we get the following: value howMany0 10130 1 10072 2 9990 3 9842 4 10174 5 9930 6 10059 7 9954 8 9891 9 9958 In each case, the number of appearances is within about 1% of the expected value (10,000), so we conclude that the random numbers are probably uniform.
|
||
Home ![]() ![]() |