简体   繁体   English

我的程序崩溃了,我找不到原因

[英]My program is crashing, I can't find why

I made a program to implement fraction in c++. 我编写了一个程序来在c ++中实现分数。 I made it because it's a kind of homework from a c++ lesson i'm following at home. 我之所以做到这一点,是因为这是我在家学习的C ++课程中的一种家庭作业。 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. m_numer的值在两个分区之间变化。 For instance, if you have denom = 20 and numer = 10 , the line 例如,如果您有denom = 20denom = 20 numer = 10 ,则该行

m_numer = m_denom % m_numer

assigns m_numer = 0 . 分配m_numer = 0 Then you get division by zero on calculation of m_denom . 然后在计算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 . 附带说明一下,考虑抛出异常而不是在cout上编写,那样,如果numer == 0则不会有带有虚假值的构造对象。

Also, numerator is the name for top of the fraction and not the bottom. 同样,分子是小数顶部而不是底部的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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