Average Function

Apr 6, 2012 at 3:31am
I need some help working on a program. I am to pass 2-10 numbers which calculate an average. I don't have to pass all the numbers but have to pass at least 2. I can pass either all integers or all float values. Is anyone willing to help me in the right direction with this program?

Thanks!


Apr 6, 2012 at 4:39am
Just sum all the numbers as you get them from the user (no need to use an array or anything). The average would then be sum / n, where n would be the amount of numbers entered. You'll need to cast one of the operands to a float in the average calculation to avoid truncation.
Apr 6, 2012 at 5:15am
#include <iostream>
using namespace std;

int main ()
{
int sum = 0;
int average = 0;
int score [10];
int k;
int avg(int a[])

//int sum = 0;
// int average = 0;
for (k = 0; k<10; k++)

{
cout <<"Enter score for 10 test:"<< (k+1) <<endl;
cin>> score [k];
average = avg(score)
sum = sum + score[k];
}
average = sum/10;
for (k=0; k<10; k++)
cout<<"score for test:"<<(k+1)<<"is"<<score[k]<<endl;
}
int avg (int a[size])
{
cout<<"The average for all 10 test is"<<average<<endl;
return 0;
}



Would This work or not? I understand some parts but some I don't so any help is appericated!!
Apr 6, 2012 at 3:58pm
this would only do the avg for integers ... like 8, 6, 10 not 8.5 , 7.3 or anything like that ... and if i'm not wrong ( and i'm pretty sure i'm not)you must declare functions outside any other function ... so declaring int avg(int a[]) inside main() isn't correct
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
int main()
{
float currScore ;
float score = 0 ;
//get number of grades
short k;
cout <<"how many scores do you want to enter ? \n" ;
cin>> k ;

for (int i=0; i<k; i++) //you will get all the k scores like this
{
cout<<"score for test:"<<(i+1)<<"is " ; /*by this you request the user to input a new score*/
cin>> currScore ;
/*add the last score that the user inputed to the total score so you can divide it later */
score += currScore ; // this is the same as score = score + currScore ; 
}
score = score / k ; /*by dividing score to k you will get the average*/
cout << "The average for all the " << k <<" tests is " <<score <<endl ;
return 0 ;
}

I used short because the number of scores won't exceed 30 000 and i used float so the user can input numbers like 6.5 , 8.4 and so on

Hope this helped .
Last edited on Apr 6, 2012 at 4:01pm
Apr 6, 2012 at 4:22pm
btw ... if u need help with anything else ... PM me ... i'll be glad to help you ... or at least try
Topic archived. No new replies allowed.