-1
#include <iostream>
using namespace std;

int g_c_d(int n, int d);

class Fraction
{

private:
  //variables to store numerator and denominator
  int num;
  int denom;

public:
  Fraction(){}
  Fraction(int num): num(num) {}
  Fraction(int num, int denom): num(num), denom(denom) {}

  void set_num(int n){ num = n;}
  void set_denom(int d){ denom = d;}

  int get_numerator() const {return num;}
  int get_denominator() const {return denom;}
};

  int g_c_d(int n, int d){
    return d == 0? n : g_c_d(d, n % d);
 }

istream &operator>> (istream &input, Fraction &f)
{
  int n, d;
  char slash;
  input >> n;
  input >> slash;
  input >> d;

  if (d == 0) {n = 0;} //if denom is 0; fraction = 0/0
  f = Fraction(n, d);
  return input;
}

ostream &operator<<(ostream &output, const Fraction &frac)
{
  return output << frac.get_numerator() << "/" << frac.get_denominator();
}


int main()
{
   int n, d;
   Fraction frac;

   int gcd;
   n = frac.get_numerator();
   d = frac.get_denominator();
   gcd = g_c_d(frac.get_numerator() , frac.get_denominator());

   cout << "Enter a fraction" << endl;
   cin >> frac;
   frac.set_num(n/gcd);
   frac.set_denom(d/gcd);
   cout << "your fraction is: ";
   cout << frac << endl;

   return 0;
}

Hi im trying to simplify fractions entered by a user. However everytime I enter a fraction that is to be simplified the output returned is "1/0".

Can some one please help, it'll be massively appreciated!

frag r33f
  • 35
  • 4

3 Answers3

2

The problem is that you do all your computations on frac before asking the user to input a fraction — and then you overwrite whatever the user inputs. You need to move this bit:

   cout << "Enter a fraction" << endl;
   cin >> frac;

much, much higher up.

ruakh
  • 175,680
  • 26
  • 273
  • 307
0

When you are setting up the code you have:

Fraction frac;

This calls the default constructor for Fraction. Because you never initialized the members in the constructor you get the default initizliation for the int type which is 0. Then:

n = frac.get_numerator();
d = frac.get_denominator();

This makes n and d 0. From that point onwards you are using those values of n and d. These values however are not the values from the user inputted frac but are just the values you get from the defaults. Change your code to read in the user inputted value for frac before you do any calculations.

The main lesson to learn here is to make sure you don't use uninitialized variables. Generally speaking when you compile with all warnings enabled this is the sort of thing that compilers will warn about.

shuttle87
  • 15,466
  • 11
  • 77
  • 106
0

You may be diving by zero because the default constructor doesn't assign value to the denominator. In the case where the denominator is set to zero, the gcd() function will divide by zero, on the first time in main.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154