As a beginner of C++, i cannot handle this project smoothly, please correct my code!
Write a class of fraction. Your fraction should provide the methods read(), print()
and the friend operator +. The read() method will read from the keyboard the integral
part, the numerator and the denominator respectively. The print() method will print
the fraction in the form afb/cg.
Finding the greatest common divisor between the numerator and denominator. Use recursion to implement the gcd() function.
The class fraction will look like:
class fraction
{
public:
fraction(); //constructor for initialize
void read(); //read 3 int from keyboard for the fraction
void print(); //print the fraction on screen
friend fraction operator +(fraction, fraction); //fraction add
private:
int integral, numerator, denominator;
}
Write a program using this class to first read from the input the number of fraction to
be added. Then create a dynamic array of the fraction object, and perform addition.
================================
#include <cstdlib>
#include <iostream>
using namespace std;
int gcdr(int m, int n);
int gcd(int m, int n);
class fraction {
public:
fraction(); //constructor for initialize
void read(); //read 3 int from keyboard for the fraction
void print(); //print the fraction on screen
friend fraction operator +(fraction, fraction); //fraction add
private:
int integral, numerator, denominator;
};
fraction::fraction() {
integral, numerator, denominator = 0;
}
void fraction::read() {
cin >> integral >> numerator >> denominator;
}
void fraction::print() {
cout << integral << "{" << numerator << "/" << denominator << "}" << endl;
}
int gcd(int m, int n) {
if (m == 0 && n == 0)
return 0;
if (m < 0)
m = -m;
if (n < 0)
n = -n;
return (gcdr(m, n));
}
int gcdr(int m, int n) {
if (m == 0)
return (n);
if (n == 0)
return (m);
return (gcd(n, m % n));
}
fraction operator + (fraction, fraction) {
fraction fraction1, fraction2, fraction_sum;
int a, b, c, d, e, f, g, h, i;
a = fraction1.integral;
b = fraction1.numerator;
c = fraction1.denominator;
d = fraction2.integral;
e = fraction2.numerator;
f = fraction2.denominator;
g = fraction_sum.integral;
h = fraction_sum.numerator;
i = fraction_sum.denominator;
b = (a * c + b) * f;
cout << b << endl;
e = (d * f + e) * c;
cout << e << endl;
i = c*f;
cout << i << endl;
g = (b + e) % i;
cout << g << endl;
h = (b + e) / i;
cout << h << endl;
h = h/gcd(h,i);
i=i/gcd(h,i);
fraction_sum.integral = g;
fraction_sum.numerator = h;
fraction_sum.denominator = i;
cout << g << h << i << endl;
return fraction_sum;
}
int main() {
fraction sum, x, temp;
int n = 0, i = 2;
cout << "Enter number of fractions:" << endl;
cin >> n;
cout << "Enter fraction 1:" << endl;
temp.read();
while (i <= n) {
cout << "Enter fraction " << i << ":" << endl;
x.read();
sum = x + temp;
temp = sum;
i++;
}
sum.print();
return 0;
}