Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

one function

Status
Not open for further replies.

nylonelyguy

Technical User
Sep 9, 2003
7
US
here is my program, it is only returning one value. can someone look at it please and tell me what im doing wrong.

note: only one function allowed, not allowed to use if statment, or global vaiable.

#include <iostream.h>
int calculate (int &, int &, int &);
void main()
{
int a,b,c;
cout<<"Enter 3 integers numbers: ";
cin>>a>>b>>c;

cout<<" the sum of the 3 numbers is: "<<calculate(a,b,c);
cout<<" the product of the 3 numbers is: "<<calculate(a,b,c);
}
int calculate (int &a, int &b, int &c)
{
int sum, pro;

sum= a+b+c;

pro=a*b*c;


return sum;


}
 
A function can only return one value. If you have to use the same function for both sum and product (not necessarily good design, but for an assignment ok) then you would normally want some sort of flag that tells the function which value to return. However, you said you can't use an if statement either, so I'm not sure how it could be done (unless they are trying to get you to use the ? operator).

On second thought, it looks like you might be learning references, so maybe the assignment wants you to use references to get the results of the calculations. I'm guessing that's it. Hope the hint helps.
-------------

On a side note, <iostream.h> and void main() are fine if they work for you, but they are not standard C++. You might want to start the habit of using the correct code according to the standard, since it will likely make your life easier if you continue to program. The standard C++ alternative to <iostream.h> is <iostream>. You will also have to add "using namespace std;" or a more appropriate alternative for your existing code to work. Also, in standard C++, main returns an int, so it should be int main() instead of void main().
 
Couldn't you just move the cins and couts into the calculate function, make sum and pro local variables there and not global, and do everything there. Main becomes merely a single call to calculate.
 
or have the function return a std::pair<int,int> where first is the sum and second the product.

/Per

&quot;It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure.&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top