Robson » Little Red Book » Statistics #1

Chapter 8 - Question 1

Design a program to create a file of random variables that could be used to represent the heights and weights of a group of students.

The values should be between a sensible lower and upper bounds and be approximately normally distributed.

The program should be pre-set to the number of values required.

Solution 1

File manipulation is one of the areas of C++ I've yet to use, so this problem provided a decent reason to start learning about it.

This code generates 50 records containing a random weight and height within a set min/max range. The output file can be used in Statistics #2.

#include <iostream.h>
#include <fstream.h>
#define RECORDS 50
 
int main()
{
   ofstream result_file;
   result_file.open("8-1-data.txt", ios::out); // create or overwrite
   for (int n = 0; n < RECORDS; n++)
       result_file << ((50 * rand()) / RAND_MAX) + 130 // heights
                   << " "
                   << ((50 * rand()) / RAND_MAX) + 90 // weights
                   << endl;
   result_file.close();
}    

Here's an example output file.

Log

© 2004-17 robson | cc unless stated