calculating array
I'm just learning array and I wanted to input 5 numbers and find the average. Here is what I have so far:
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
|
#include <iostream>
double comavg(double x[], int n);
using namespace std;
int main(){
double sum = 0.0;
double grade[5];
for(int i = 0; i < 5; i++){
cout << "Enter a number: ";
cin >> sum;
grade[i] += sum;
}
cout << comavg(grade, 5) << endl;
system("pause");
}
double comavg(double x[], int n){
double average = 0.0;
for(int i = 0; i < n; i++){
average += x[i];
average /= 5;
return (average);
}
}
|
Its giving me a long negative number. Thanks you.
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
|
# include <iostream>
using namespace std;
double comavg(double x[], int n);
int main()
{
double grade[5];
for(int i = 0; i < 5; i++)
{
cout << "Enter a number: ";
cin >> grade[i];
}
cout << "The average is : " << comavg(grade, 5) << endl;
return 0;
}
double comavg(double x[], int n)
{
double average = 0.0;
for(int i = 0; i < n; i++)
{
cout << x[i] << endl;
average += x[i];
}
return average /= n;
}
|
Thanks you very much.
Topic archived. No new replies allowed.