[英]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==0
并return
变量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 = m
且m 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
. 如果
n
和m
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
. 另一方面,如果
m
和n
是e
倍数,则因为m mod n = m -n * (m div n)
也是e
倍数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.