Re: Can you fix this code???
You have to assign avg to f after calculating avg.
Re: Can you fix this code???
The average should be the sum divided by the number of items. Since count starts at zero, the average is:
average = sum / (count + 1);
It also looks as if you want the difference between the average and the current number entered, not the difference
between the sum and the average.
When coding, try to use meaningful names, and use plenty of spaces to make it readable. In C++, it is good practice to
wait to declare variables until they are needed, and initialize them immediately. For clarity, each variable should be
declared on a separate line.
Here is my version of your program:
#include <iostream.h>
#include <conio.h>
#include <limits.h> // contains INT_MAX and INT_MIN
int main() // main has an int return value
{
// clrscr(); // VC++ doesn't have this
cout << "How many numbers would you like to enter?\t";
int maxEntries = 0;
cin >> maxEntries;
if (maxEntries <= 0) // Bail out if bad entry!
return 0;
int sum = 0;
int minNumber = INT_MAX; // Start at largest
int maxNumber = INT_MIN; // start at smallest
for (int count = 0; count < maxEntries; count++)
{
cout << "\n\nEnter a number please:\t";
int number = 0;
cin >> number;
sum += number;
// Ensure floating point arithmetic by casting one operand to float
float average = (float)sum / (count + 1);
cout << "\nAverage of these numbers is " << average;
float difference = number - average;
cout << "\nDifference between this number and the average is " << difference;
if (number < minNumber)
minNumber = number;
if (number > maxNumber)
maxNumber = number;
}
cout << "\nSmallest number is " << minNumber;
cout << "\nLargest number is " << maxNumber;
// Ensure floating point arithmetic by casting one operand to float
float totalAverage = (float)sum / maxEntries;
cout << "\nTotal Average is " << totalAverage;
cout.flush(); // VC++ needs this to ensure output before getch()
getch();
return 0;
}
hope this helps,
Dave