简体   繁体   中英

My program is crashing, I can't find why

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.

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, ie

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM