【问题标题】:why is there a SIGFPE?为什么会有 SIGFPE?
【发布时间】:2011-06-04 12:46:20
【问题描述】:

由于某种原因,它曾经可以工作。但现在我得到了一个 SIGFPE .....怎么了?

#include "usefunc.h"

long factorial(long num) {
    if (num > 1) {
        long counter;
        long fact = 1;
        for (counter = num; counter > 0; counter--) fact *= counter;
        return fact;
    }
    else return 0;
}

long combinations(long n, long k) {
    return (factorial(n)) / (factorial(k)*factorial(n-k));
}

int main()
{
    printf("How many rows of Pascal\'s triangle should I print?\t");
    int rows = GetInteger();
    long pArray[rows][rows];
    int counter;
    int counter2;
    for (counter = 1; counter <= rows; counter++)
    {
        int y = rows-counter;
        for (; y > 0; y--) printf("    ");
        for (counter2 = 0; counter2 <= counter; counter2++)
        {
            /*

                    THIS IS AN OUTPUT

            */
            printf("%9.0lu", (long) combinations(counter, counter2));
            pArray[counter][counter2] = (long) combinations(counter, counter2);
        }
        /*

                    THIS IS AN OUTPUT

        */
        printf("\n");
    }
    return 0;
}

【问题讨论】:

    标签: c signals pascals-triangle sigfpe


    【解决方案1】:

    您的阶乘返回 0,这会导致除以 0 错误。它不应该返回 1 吗?


    jcomeau@intrepid:/tmp$ cat test.c; make test;./test
    #include <stdio.h>
    int main() {
     return printf("%f\n", 1L / 0);
    }
    cc     test.c   -o test
    test.c: In function ‘main’:
    test.c:3: warning: division by zero
    Floating point exception
    

    【讨论】:

    • long 除以 long 不是浮点异常。更好的解决方法可能是在combinations 中添加一个k &gt;= 0 &amp;&amp; k &lt;= n 的检查。
    • 这是正确的 - 将整数除以零将导致 SIGFPE。有趣的是,浮点数除以零不会导致SIGFPE
    【解决方案2】:

    我认为这是您的 combinations 函数,您没有向我们展示,因为您提供的代码都没有使用任何浮点数。


    SIGFPE does not mean floating-point exception,即使这就是名字的来源。 @jcomeau 已正确确定您获得 SIGFPE 的原因。

    【讨论】:

    • @tekknolagi:好的,我在任何地方都看不到任何浮点数。但是你有一堆无用的演员表。此外,您的“组合”功能是天真的实现的,它的内部变量会在结果之前很久就溢出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2021-11-08
    • 2020-05-24
    • 2013-02-01
    • 2011-11-08
    • 2012-01-02
    相关资源
    最近更新 更多