[英]Runtime error while running a simple code in GCC compiler for C
Following is the code: 以下是代码:
#include <stdio.h>
void main ()
{
int n1, n2, min, GCD, i;
printf("Enter two nos. : ");
scanf(" %d %d", &n1, &n2);
min=(n1<n2)? n1: n2;
for (i=0, i<min; ++i)
{
if(n1%i==0 && n2%i==0)
GCD=i;
}
printf("GCD is %d", GCD);
}
Please point out the mistake which is causing runtime error. 请指出导致运行时错误的错误。
The modulus operator %
will be problem when i
is equal to zero. 当
i
等于零时,模数运算符%
将是问题。 There is no need to start with i = 1
, every number is divisible by 1
. 无需以
i = 1
开头,每个数字都可以被1
整除。 Start with i = 2
. 从
i = 2
开始。
Also, you have a problem in the for
loop, most likely due to a typo. 另外,您在
for
循环中遇到问题,很可能是由于输入错误造成的。
for (i=0, i<min; ++i)
^^^ That should be ;
Here's the loop with both fixes: 这是两个修复程序的循环:
for (i=2; i<min; ++i)
{
if(n1%i==0 && n2%i==0)
GCD=i;
}
Other suggestions to improve your code: 其他改善代码的建议:
main
to int
. main
的返回类型更改为int
。 That' what the standard expects. GCD
to 1
instead of leaving it uninitialized. GCD
初始化为1
而不是未初始化。 You know that it has to be at least 1
. 1
。 for (i=0, i<min; ++i) is wrong syntax
for (i=0; i<min; ++i) is correct syntax
(n1%i)
is actually dividing by 0; (n1%i)
实际上被0除; this is the reason for runtime error 这是运行时错误的原因
return type of main is int
as per standard 根据标准,main的返回类型为
int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.