Nov 21, 2015 at 1:23pm UTC
I'm trying to write a program that simplifies fractions. The problems is that when I put in a denominator of 0, It's supposed to give an error message. I put it in my constructor but it's not using it at all. Any ideas as to what I'm doing wrong. I'm beating my head against a wall at this point.
#include <iostream>
#include <cmath>
#include <sstream>
using namespace std;
class Fraction
{
private:
int numerator;
int denominator;
public:
Fraction()
{
numerator=1;
denominator=1;
}
Fraction(int num, int denom)
{
numerator = num;
denominator = denom;
if (denominator==0)
{
cout << "Error: Can't divide by 0";
exit(0);
}
}
void setNumerator(double num)
{
numerator=num;
}
void setDenominator(double denom)
{
denominator=denom;
}
double toDecimal(double num, double denom)
{
return num/denom;
}
string toString(double number)
{
string String=static_cast<ostringstream*>(&(ostringstream() << number) )->str();
return String;
}
double reduce(double num, double denom)
{
if(denom==0)
return num;
else
return reduce(denom, fmod(num, denom));
}
};
int main()
{
double num;
double denom;
Fraction frac;
cout << "Please enter the numerator: ";
cin >> num;
frac.setNumerator(num);
cout << "Please enter the denominator: ";
cin >> denom;
frac.setDenominator(denom);
cout << "Your fraction is: " << num << "/" << denom << "." << endl;
cout << "As a decimal your fraction is: " << frac.toDecimal(num, denom) << "." << endl;
cout << "Your fraction as a string is: " << frac.toString(num) << "/" << frac.toString(denom) << "." << endl;
int gcd = frac.reduce(num, denom);
cout << "Your fraction reduced is: " << num/gcd << "/" << denom/gcd << "." << endl;
return 0;
}
Nov 21, 2015 at 2:23pm UTC
Morning. It's because when you instantiate your Fraction you're calling the 'wrong' constructor:
This:
Fraction frac;
calls this:
1 2 3 4 5
Fraction()
{
numerator=1;
denominator=1;
}
not this:
1 2 3 4 5 6 7 8 9 10 11
Fraction(int num, int denom)
{
numerator = num;
denominator = denom;
if (denominator==0)
{
cout << "Error: Can't divide by 0" ;
exit(0);
}
}
Therefore you want to do something like this:
1 2 3 4 5 6 7 8 9 10 11 12
double num;
double denom;
cout << "Please enter the numerator: " ;
cin >> num;
//frac.setNumerator(num);
cout << "Please enter the denominator: " ;
cin >> denom;
//frac.setDenominator(denom);
Fraction frac(num, denom);
also be wary stuff like this, particularly when dividing:
numerator is an int, but num is a double for some reason.
Last edited on Nov 21, 2015 at 2:24pm UTC