1

为什么这个程序不起作用?这是使用递归函数的简单最大公约数程序。它编译没有错误,但是当我运行 program.exe 时它只是崩溃:“程序已停止工作”。我已经在代码块和 Notepad++ 上尝试过。我使用 gcc 编译器。

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

int gcd(int,int);
int main(int argc,const char* argv[]){
int a;
int b;
a = atoi(argv[1]);
b = atoi(argv[2]);
printf("The greatest common divisor of %d and %d is %d\n",a,b,gcd(a,b));
return 0;
}
int gcd(int a,int b){
    if(a==0)
        return a;
    else
        return gcd(b, a%b);
}
4

2 回答 2

4

你有这个错误:

  if(a==0)

应该

  if(b==0)

你想检查除数不是0,不是被除数。

于 2013-09-30T19:39:52.600 回答
0

在您的程序中,您需要添加检查 a>b 条件以消除除以 0 问题

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

int gcd(int,int);
int main(int argc, char ** argv[]){
int a;
int b;
int c;
a = atoi(argv[1]);
b = atoi(argv[2]);
if (a<b)
    {                            //swapping if a<b
        c=a;
        a=b;
        b=c;
    }
printf("The greatest common divisor of %d and %d is %d\n",a,b,gcd(a,b));
return 0;
}
int gcd(int a,int b){
    int r1=a%b;
    while(r1>0)
        return gcd(b,r1);
        return b;
}
于 2014-02-01T12:34:23.377 回答