patterncppMinor
Computing the average of several numbers
Viewed 0 times
thenumbersaverageseveralcomputing
Problem
I am learning C++. This is a simple program I had to write for class. Is there anything I should fix?
#include
using namespace std;
int main()
{
const int ListSize = 5;
int ValuesProcessed = 0;
float ValueSum = 0;
cout > Value;
ValueSum += Value;
++ValuesProcessed;
}
float Average = ValueSum / ValuesProcessed;
cout << "Average: " << Average << endl;
return 0;
}Solution
This is quite good for a homework exercise.
I would recommend a
This puts all the logic of iteration together where you are less likely to overlook
some detail, unlike the
the test for termination of the loop, and setting
iteration are done in three different places.
I tend to follow the philosophy of declaring things as close to where they are used
as possible, so I would move the declaration and initialization of
the "Please enter" printout. But I don't think there's a strong argument for doing this.
(It would merely swap the order of two lines of code, not a big deal.)
Contrary to another answer, I like your decision to declare
function. (It's another example of "declaring things as close to where they are used
as possible".) Although
single loop in the program, or to put it another way, the length of a list of inputs
that the program is about to read.
I would recommend a
for loop instead of the while:for (int ValuesProcessed = 0; ValuesProcessed < ListSize; ++ValuesProcessed) {This puts all the logic of iteration together where you are less likely to overlook
some detail, unlike the
while loop where the initial value of ValuesProcessed,the test for termination of the loop, and setting
ValuesProcessed for the nextiteration are done in three different places.
I tend to follow the philosophy of declaring things as close to where they are used
as possible, so I would move the declaration and initialization of
ValueSum afterthe "Please enter" printout. But I don't think there's a strong argument for doing this.
(It would merely swap the order of two lines of code, not a big deal.)
Contrary to another answer, I like your decision to declare
ListSize in your main()function. (It's another example of "declaring things as close to where they are used
as possible".) Although
ListSize is a "constant" in the sense that you have declared itconst (which I think is a good idea), it is really just the end condition of asingle loop in the program, or to put it another way, the length of a list of inputs
that the program is about to read.
Code Snippets
for (int ValuesProcessed = 0; ValuesProcessed < ListSize; ++ValuesProcessed) {Context
StackExchange Code Review Q#65145, answer score: 5
Revisions (0)
No revisions yet.