|
-
March 2nd, 2006, 12:20 PM
#1
Passing # of Arguments
I was wondering if there were a function to pass the # of arguments in a parameter to a value of a variable.
For instance, lets say I want a program that does averages, the main function collects the #'s, and then theres a getAvg function which does the math
Is there a way for one of the arguments in getAvg to be the # values being passed to it?
-
March 2nd, 2006, 12:24 PM
#2
Re: Passing # of Arguments
You could store the numbers in say, a std::vector and when the data collection is done, just calculate the average of the numbers in the container.
-
March 2nd, 2006, 01:18 PM
#3
Re: Passing # of Arguments
you could write getAvg() to use a variable number of arguments, but the std::vector is a lot better and easier to implement solution for c++ programs. There must be at least one non-variable argument. and you need to devise for that function to know where the last argument is -- maybe pass -1 or something else that will not occur normally in the other arguments. for variable arguments you need to use functions in stdarg.h . Scroll down the page of that link and you will find some example programs.
Code:
int getAvg(int a, ...);
int main()
{
int n = getAvg(1,2,3,4,5,6,-1);
}
-
March 3rd, 2006, 01:26 AM
#4
Re: Passing # of Arguments
Can you help me with my homework assignment?, Before you post!, Use code tags, How to post!, Codeguru technical FAQs, C++ FAQ Lite, Stroustrup: C++ Style and Technique FAQ, Guru of the Week, Comeau C and C++ FAQs, Comeau C++ Templates FAQs, CUJ @ DDJ, Spam threshold
My Blogs : Learning C++ is fun | Abnegator's reflections
Open Threads : C++ Aha! Moments | Nature of work in C++?
-
March 3rd, 2006, 02:17 AM
#5
Re: Passing # of Arguments
The problem I see is that for "the main function collects the #'s" to work, there must be some way to store the numbers. Or, if the average is the arithmetic mean, one can just sum and keep a counter of the number of numbers input, then divide. That doesnt even need a container (aside from the sum), but "average" here is rather vague.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|