c - 浮点异常: 8

标签 c

为什么我收到错误:浮点异常:8

#include<stdio.h>
//grid problem
int fact(int n)
{

    int i,f=1;
    if(n==0)
        return 1;
    for(i=1;i<=n;i++)
        f*=i;
    return f;
}

int uniquePaths(int A, int B) {
    float m;
    m=fact(A+B-2)/(fact(A-1)*fact(B-1));
    return m;
}

int main(int argc, char const *argv[])
{
    int a,b;
    //aXb grid
    scanf("%d%d",&a,&b);
    printf("%d\n",uniquePaths(a,b) );
    return 0;
}

最佳答案

如果使用函数断言添加前置条件和后置条件,则可以确保参数和函数结果具有合理的值:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

//grid problem
int fact(int n)
{
    assert(n >= 0);
    int i, f = 1;
    if (n == 0) {
        return 1;
    }
    for (i = 1; i <= n; i++) {
        f *= i;
    }
    assert(f >= 1);
    return f;
}


int uniquePaths(int A, int B)
{
    assert(A >= 1);
    assert(B >= 1);
    int q = fact(A - 1) * fact(B - 1);
    assert(q > 0);
    int m = fact(A + B - 2) / q;
    assert(m >= 1);
    return m;
}


int main(int argc, char const *argv[])
{
    int a, b;
    //aXb grid
    int n = scanf("%d%d", &a, &b);
    if (n == 2) {
        printf("%d\n", uniquePaths(a, b));
    } else {
        fprintf(stderr, "invalid input\n");
        exit(1);
    }
    return 0;
}

例如,在我的机器上,使用输入 10 10 运行上面的程序将导致

t: t.c:16: int fact(int): Assertion `f >= 1' failed.
Aborted

(但是我不知道为什么会出现浮点异常。)

关于c - 浮点异常: 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44403942/

相关文章:

c - 异或字节数组(Shellcode)

c - GtkListStore - 如何将文本居中?

c - 有没有办法获取短路数据的最后一个字节并将其保存到字符中

c - IAR EWARM PC-LINT 禁止来自包含 -header 选项的 header 的消息

c - 将寄存器的内容读入 C 变量时的奇怪行为

c - 如何从数组中获取字符串

c - 指针到指针的地址和算术

c - fopen(file, "w") 是否写入新 block ?

c - 机器上int数据类型的宽度

c - execve '/bin/sleep'命令卡住