简体   繁体   English

C程序中的浮点异常

[英]floating point exception in c program

while running this code I am getting floating point exception pls explain why it is coming so. 在运行此代码时,我遇到了浮点异常,请解释为什么会这样。

#include <stdio.h>
int gcd(long int, int);
int main() {
    int t, n, a, i;
    long int abc;
    scanf("%d", &t);
    while (t--) {
        abc = 1;
        scanf("%d", &n);
        abc = n * (n - 1);
        for (i = n - 2; i > 1; i--) {
            a = gcd(abc, i);
            abc = ((abc * i) / a);
        }
        printf("%ld \n", abc);
    }
    return 0;
}
int gcd(long int a, int b) {
    if (b == 0)
        return a;
    else {
        return (b, a % b);
    }
 }

The else part in gcd function is bogus. gcd函数中的else部分是伪造的。 You probably wanted to call gcd recursively and instead you are returning a % b . 您可能想递归调用gcd ,而是返回a % b And as a result if a % b == 0 you divide by 0 on line 13. 结果,如果a % b == 0 ,则在第13行除以0。

The expression (b, a % b) is evaluated as two subexpressions separated by comma operator. 表达式(b, a % b)被评估为两个用逗号运算符分隔的子表达式。 The value of b is forgotten and the value of the whole expression becomes a % b . b的值被遗忘,整个表达式的值变为a % b

The correct version: 正确的版本:

int gcd(long int a, int b) {
    if (b == 0)
        return a; 
    else {
        return gcd(b, a % b);
    }
 }

You should change a few things: 您应该更改一些内容:

1) if(a == 0) instead of b==0 and return variable b 1) if(a == 0)而不是b==0return变量b
2) Use recursion gcd(b%a, a) 2)使用递归gcd(b%a, a)

if (a == 0)
       return b;
    else {
        return gcd(b%a, a);
    }

And you can also use this short version 您也可以使用此简短版本

return  a ? gcd(b%a,a) : b;

Proof: 证明:

We have m = n * (m div n) + m Mod n . 我们有m = n * (m div n) + m Mod n

This equation is correct even if n = 1 , because m div 1 = m and m mod 1 =0 . 即使if n = 1 ,该方程式也是正确的,因为m div 1 = mm mod 1 =0

If n and m mod n it's multiple of d , also m is multiple of d , because n * (m div n) and m mod n / d . 如果nm mod n是d的倍数,则m也是d倍数,因为n * (m div n)m mod n / d

On the other hand if m and n is multiple of e , to because m mod n = m -n * (m div n) is also multiple of e . 另一方面,如果mne倍数,则因为m mod n = m -n * (m div n)也是e倍数。

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

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