Hi guys.
I have a problem with functions.
To put it simply. If I create a
void
function that does something when I call it, and I want to print (i.e. cout) its result in
int main()
, I can NOT. I get an error. For example:
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 33 34 35
|
#include <iostream>
#include <cmath>
using namespace std;
struct fraction
{
int numerator;
int denominator;
};
void sum(int x, int y, int z, int k)
{
double f3;
f3 = ((double)x/y)+((double)z/k);
cout << "sum of the two fractions = ";
}
int main()
{
fraction f1, f2;
cout << "enter the numerator and demominator of the first fraction: ";
cin >> f1.numerator >> f1.denominator;
cout << "enter the numerator and demominator of the second fraction: ";
cin >> f2.numerator >> f2.denominator;
cout << sum(f1.numerator, f1.denominator, f2.numerator, f2.denominator);
return 0;
}
|
Now, if you run this, you will get an error regarding
|
cout << sum(f1.numerator, f1.denominator, f2.numerator, f2.denominator);
|
The fix is simple.
1) You can replace the line that is causing the error with:
|
sum(f1.numerator, f1.denominator, f2.numerator, f2.denominator);
|
i.e. DELETING "cout"
And, inside the definition of the function
sum()
, at the end of it, write:
OR
2) replace the function type of
void
with
double
.
And then at the end of the function, write
return f3;
.
And now, you can write "cout << sum(....)" without any errors.
But, I do not want to do either of these compromises! I want to keep the function as a
void
type and be able to cout the function in
int main()
.
How can I do that?? Or is it the case that if you have a function of type
void
, then you simply can not cout it?