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

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 に答える