2013-09-30 153 views
1

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

#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); 
} 
+0

的就是你得到的错误消除鸿沟?在运行程序时传递命令行变量? – sujin

+0

你用有效的参数运行程序吗? –

回答

4

你有这样的错误:

if(a==0) 

应该

if(b==0) 

您要检查除数是不是0,不派息。

+1

崩溃可能是由'a%b'的0错误除。 – jxh

+1

@jxh这正是我的观点 – ouah

+1

@jxh就是这样。 –

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; 
}