I did not get right result for object f3 when I see the f3 using show_fraction() function in the below code: I am confused. I want to access the sum of f1 and f2 fraction that is stored in f3.But when i see the result in f3 it shows 0/0 in result using fraction_show() function
#include <iostream>
using namespace std;
class fraction
{
private:
float numerator;
float denominator;
char ch;
public:
void get_fraction()
{
cout << "\nEnter the fraction ( in format n/d ): ";
cin >> numerator >> ch >> denominator;
}
void show_fraction()
{
cout << " Fraction is: " << numerator << "/" << denominator;
}
fraction sum(fraction &f, fraction &d) // returns sum of two fractions
{
fraction ff; // to hold the result
// denominator of result
ff.numerator = (f.numerator * d.denominator f.denominator * d.numerator);
ff.denominator = f.denominator * d.denominator; // numerator of result
return ff;
}
};
int main() // program to test the class
{
fraction f1, f2, f3; // three objects of type fraction created
char ch1;
do
{
f1.get_fraction();
f2.get_fraction();
f3.sum(f1, f2);
cout << "\nSum of ";
f3.show_fraction(); // shows the result ( wrong result)
cout << "\nDo you want to continue ( y/n ): "; // If the user want to continue
cin >> ch1;
} while (ch1 != 'n');
cout << endl;
return 0;
} // end of main
CodePudding user response:
I don't like this style of coding, but at least this works
void sum(fraction &f, fraction &d) // calculates sum of two fractions
{
numerator = (f.numerator * d.denominator f.denominator * d.numerator);
denominator = f.denominator * d.denominator;
}
then
f3.sum(f1, f2);
I would prefer something like this
friend fraction sum(fraction &f, fraction &d) // returns sum of two fractions
{
fraction ff; // to hold the result
// denominator of result
ff.numerator = (f.numerator * d.denominator f.denominator * d.numerator);
ff.denominator = f.denominator * d.denominator; // numerator of result
return ff;
}
with this version you need to change the way you call the function
f3 = sum(f1, f2);
I'm not sure which you were intending but you wrote something that was half way between the two versions.