AVERAGE FUNCTON

hello I have been having trouble writing a program to ask a user how many tests theyve taken, then calculate the average of that, and then return it to main (I have to use a function).
If anyone can help itd be much appreciated.
closed account (18hRX9L8)
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>

int Average (int tests [], int numberof);
int Average (int tests [], int numberof)
{
	int count,aver,total=0;
	for(count=0;count<numberof;count++)
	{
		total+=tests[count];
	}
	aver=total/numberof;
	return(aver);
}

main()
{
	int numberof,counter,average;
	std::cout<<"how many tests have you taken?  ";
	std::cin>>numberof;
	int tests[numberof];
	for(counter=0;counter<numberof;counter++)
	{
		std::cout<<"Test #"<<counter+1<<" Percentage?  ";
		std::cin>>tests[counter];
	}
	average=Average(tests,numberof);
	std::cout<<std::endl<<std::endl<<"Average of all tests: "<<average;
}
@usandfriends


Function main shall have return type int

C++ does not allow to specify a non-const expression as the size of an array. So this declaration is invalid.

int tests[numberof];

Also there is no need to declare function Average two times.
Last edited on
closed account (18hRX9L8)
My compiler lets me do all this stuff.
Sorry for teaching bad things. I won't anymore.

My new code is posted after Branflakes' post.
Last edited on
I'm sorry.

It's fine if you prefer a compiler that lets you do all of this stuff, but problems arise when you give newbies code that will only work for your compiler. Anything non-standard like everything you mentioned will jeopardize the portability of the code.

Also,
I'm sorry, I have many bad habits.

Why are you teaching newbies these "bad habits" if you know they are bad?

Not trying to incite any rage here, just giving my two cents. I'm also sure that vlad wasn't trying to either, so I'm confused why you took it so personally.
Last edited on
closed account (18hRX9L8)
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>

int Average (int tests[numberof])
{
	int count,aver,total=0;
	for(count=0;count<numberof;count++)
	{
		total+=tests[count];
	}
	aver=total/numberof;
	return(aver);
}

int main()
{
	int numberof,counter,average;
	std::cout<<"how many tests have you taken?  ";
	std::cin>>numberof;
	int tests[numberof];
	for(counter=0;counter<numberof;counter++)
	{
		std::cout<<"Test #"<<counter+1<<" Percentage?  ";
		std::cin>>tests[counter];
	}
	average=Average(tests[numberof]);
	std::cout<<std::endl<<std::endl<<"Average of all tests: "<<average;
	return(0);
}


Fixed my code for vlad's mention.
It doesn't compile on my compiler but i hope it compiles on yours!

EDIT: Actually, every program I see on these forums that has functions that has arguments as arrays are like this void function (int array [], int size) so yeah...
Last edited on
Topic archived. No new replies allowed.