views
Setup and Planning
Plan your program. The first step to make this program is to plan how the program will work. If the numbers that will be calculated are long, floating-points then the double data type can be used to store numbers. If however, they are large integers, it is more appropriate to use long longs.
Setup a basic skeleton program. In this step, include the iostream header file. Write out the main function: this will be where most of your code will be written.
#include
Make an outline of the basic flow of the program. Use comments to take notes on what needs to be done. This will make it easier for you to fill in your code as you progress along. In larger projects, you might forget what your overall goal is. Comments help out here.
#include
Writing the Code
Declare and read an int variable (n) to store the number of values in the data set. Use cin to read input. ... // read number of values int n; cout << "Enter the number of values in the data set:\n"; cout << ": "; cin >> n; cin.ignore(); // TODO read data and accumulate the sum ... You can output string literals to prompt the user using cout. On some systems, you may need to add the cin.ignore(); statement to tell the buffer to ignore the newline or return-carriage from the Enter-key.
Use a loop to iterate from 0 to n, reading data and accumulating the sum. We first need to declare a variable to store the sum and initialize it to 0.0. We then use a for-loop, setting a temporary variable i to iterate from 0 to n and using x to read in temporary values. These temporary values are then added to the sum. ... // read data and accumulate the sum double sum = 0.0; for (int i = 0; i < n; i++) { double x; cout << "Enter the value #" << i+1 << ":\n"; cout << ": "; cin >> x; cin.ignore(); sum += x; } // TODO take the average of the sum to determine the mean ... Again, you may prompt the user for input using cout.
Determine the mean by dividing by the number of values in the data set. ... // take the average of the sum to determine the mean double mean = sum / n; // TODO print output ... Note that if you declared sum to integer data types, integer division will be performed and there may be a loss of accuracy. To work around this, cast sum into a float or double first before dividing.
Print the output to the user, showing the result. Use the cout stream to show your final results to the user. ... // print output cout << "Average/Mean = " << mean << '\n'; return 0; ...
Review, comment, and clean your code.
#include
Comments
0 comment