Since variable
judge
is not initialized therefore
m
is holding a garbage value. When your functions for finding maximum and minimum value will run they will iterate the
scores[]
array till
m
whose value can be way larger then the size of bounded
scores[]
array.
Variable
m
is not the size of
scores[]
array, it is a garbage value and when you access an index that is out of boundary your program may crash if reading that memory block is restricted. Otherwise you may get wrong result as value on that memory block can be anything.
One other thing,
Line: 74 of your code: What if the value of
judge
is 2. Dividing by zero
will also crash your program since it goes to infinite. You need to
fix this formula for calculating averages.
I have made little corrections as mentioned below:
1) local variable
judge
was holding garbage value when it was assigned to variable
m
since it was not initialized.
2) Variable
n
is useless since it is only increasing without being used anywhere in the code
3) Id of Athlete was asked twice. Before the loop and at the end of loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <iostream>
using namespace std;
int maximum(double scores[], int);
int minimum(double scores[], int);
int sumoftotal(double scores[], int);
int maximum (double scores[], int m)
{
int maxi=0;
for(int j=0;j<m;j++)
if (scores[j]>maxi)
maxi=scores[j];
return maxi;
}
int minimum (double scores[], int m)
{
int mini=0;
for(int k=0;k<m;k++)
if (scores[k]<mini)
mini=scores[k];
return mini;
}
int sumoftotal(double scores[],int m)
{
int sum=0;
for(int l=0;l<m;l++)
sum+=scores[l];
return sum;
}
int main()
{
int id=0, judge=0, m=0, i=0;
double *scores, maxi = 0.0, mini = 0.0, sum = 0.0, avgscore = 0.0;
while(true)
{
cout << "Enter the ID for Athlete" << endl;
cin >> id;
if(id <= 0)
break;
cout << "Enter the amount of judges" << endl;
cin >> judge;
scores = new double[judge];
m = judge;
cout << "Please enter the " << judge << " scores" << endl;
for(i=0;i<judge;i++)
{
cin >> scores[i];
}
maxi=maximum(scores,m);
mini=minimum(scores,m);
sum=sumoftotal(scores,m);
// What if the value of judge is 2 ??? It will be infinite ???
avgscore = (sum - maxi - mini )/(judge - 2);
cout << avgscore << " is the higher number" << endl;
}
return 0;
}
|