Program works but average keeps coming up as 0. Any help would be greatly apprec
ID: 3535194 • Letter: P
Question
Program works but average keeps coming up as 0. Any help would be greatly appreciated.
#include <iostream>
using namespace std;
float Average(int *scores, int number);
void SortTestScores(int *scores, int n);
int main()
{
int *testScores = new int[50];
float averageScore = 0;
int number, i;
cout << "Enter number of Test Scores: ";
cin >> number;
cout << "Enter Test scores: ";
for(i=0; i < number;i++)
cin >> testScores[i];
SortTestScores(testScores, number);
cout << "Sorted Test Scores: ";
for(i=0; i < number;i++)
cout << testScores[i] << endl;
cout << "Average Test Score is: " << Average << endl;
}
void SortTestScores(int *scores, int number)
{
int temp;
int i,j;
for(i=1; i < number; i++)
{
for (j=0; j < number-i; j++)
{
if (scores[j] > scores [j+1])
{
temp = scores[j];
scores[j] = scores[j+1];
scores[j+1] = temp;
}
}
}
}
float Average(int *score, int n)
{
int i;
float avg = 0.0;
for(i = 0; i < n; i++)
{
avg += score[i];
}
avg = avg/n;
return avg;
}
Explanation / Answer
you don't assign averagescore the float returned by your Average. (infact you don't even call it)
your cin >> (array) needs to be in an if statement to reject negatives.
instead of 50 you need to use "number"
(Sidenote: can you sort like that? or must you use pointer arithmetic?)
pause needs to be capitalized - use cin.get(); instead of system("PAUSE");
you should probably cast your ints as floats in the function, it might not be done implicitly.
A while loop would be more useful for inputting the scores.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.