简体   繁体   English

在C的GCC编译器中运行简单代码时出现运行时错误

[英]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: 其他改善代码的建议:

  1. Change the return type of main to int . main的返回类型更改为int That' what the standard expects. 这就是标准所期望的。
  2. Initialize 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.

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