Reputation: 39
I made a program to implement fraction in c++. I made it because it's a kind of homework from a c++ lesson i'm following at home. The program compile but will crash quickly after it was launch. I search an answer myself and all I found was that it crashes when a new object is being created. Here is the code in fault.
//a and b are for the numerators and denominator in the fraction: a/b
ZFraction::ZFraction(int numer, int denom):m_numer(numer), m_denom(denom)//this constructor made it crash
{
if(m_numer != 0)
{
m_numer = m_denom % m_numer;
m_denom = m_denom/m_numer;
}
else
{
cout << "Fraction impossible";
}
}
Why is it crashing? Thanks in advance.
Upvotes: 0
Views: 108
Reputation: 857
The value of m_numer
changes between the divisions. For instance, if you have denom = 20
and numer = 10
, the line
m_numer = m_denom % m_numer
assigns m_numer = 0
. Then you get division by zero on calculation of m_denom
. I would suggest doing the calculations with the original values, i.e.
ZFraction::ZFraction(int numer, int denom):m_numer(numer), m_denom(denom)
{
if(numer != 0)
{
m_numer = denom % numer;
m_denom = denom/numer;
}
else
{
cout << "Fraction impossible";
}
}
On a side note, consider throwing an exception instead of writing on cout, that way you will not have a constructed object with a bogus value if numer == 0
.
Also, numerator is the name for top of the fraction and not the bottom.
Upvotes: 1