// // Program name: variance // Author: B. Massingill // // Purpose: compute the variance of a sequence of numbers // // Input: // a sequence of floating-point numbers x(0), x(1), .... x(n-1) // read from standard input, terminated by end-of-file // (control-D if entered from keyboard) // (here, x(i) means "x-subscript-i") // Output: // the variance of (x(0), x(1), ... x(n-1)) -- which is the sum, // for 0 <= i <= n-1, of (x(i) - avg) squared, where // avg is the average of the x(i)'s // for example, // for input 1 2 3 4, the program should compute and // print ... // (written to standard output) // // The program assumes that n <= 20. If the user enters more than // 20 numbers, the program will print a warning message and // perform the calculation using the first 20 numbers. // #include int main() { const int MAXNUMS = 20 ; // maximum number of inputs // note the use of a "const" (constant) integer here. // we use MAXNUMS anywhere we need the maximum number of // inputs. so if we later decide to increase it to 100, // we don't go through the program and look for all the 20s, // we just change the above line. double x[MAXNUMS] ; // inputs x(i) int n = 0 ; // number of inputs so far double sum = 0.0 ; // sum of inputs so far // prompt user cout << "Enter numbers, control-D to end\n" ; // read while there is input and not too many numbers: // x[n] is always the "next" spot in the array // if n >= MAXNUMS, exit the loop (no more room in array) // otherwise if there is no more to read, exit the loop // ("cin >> x[N]" reads input and also returns true // if there was something to read, false if not) while (n < MAXNUMS && cin >> x[n]) { // increment running total, count sum += x[n] ; n++ ; // } // if n >= MAXNUMS, the user entered at least MAXNUMS numbers, // and we read MAXNUMS of them // so we want to try to read one more to see whether to print // a warning message // we need a place to read into, but we don't need to use the // value read (if any) -- so read into xtemp double xtemp ; if (n >= MAXNUMS) { if (cin >> xtemp) cout << "Warning: More than " << MAXNUMS << " numbers entered. Only the first " << MAXNUMS << " will be used.\n" ; } // now compute the average double avg ; if (n > 0) avg = sum / n ; // and now compute the variance // note that this will work even if n == 0! int i = 0 ; double variance = 0.0 ; while (i < n) { variance += (x[i] - avg) * (x[i] - avg) ; i++ ; } if (n > 0) cout << "Variance is " << variance << endl ; else cout << "No numbers entered\n" ; return 0 ; }