【问题标题】:Simple GCD program can't run简单的 GCD 程序无法运行
【发布时间】:2013-09-30 19:36:41
【问题描述】:

为什么这个程序不起作用?这是使用递归函数的简单最大公约数程序。它编译没有错误,但是当我运行 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);
}

【问题讨论】:

  • 您遇到的错误是什么?运行程序时传递命令行变量?
  • 您是否使用有效参数运行程序?

标签: c crash greatest-common-divisor


【解决方案1】:

你有这个错误:

  if(a==0)

应该是

  if(b==0)

您要检查除数不是0,而不是被除数。

【讨论】:

  • @ouah:我希望你知道,我只是指出来。另一种可能性是提问者没有向程序传递足够的参数(因为没有检查argc)。
  • 没有变化。编译后按运行时显示:程序已停止工作
  • @MishoMetreveli 您必须使用参数调用您的程序,在 Windows 上(例如):tst.exe 15 5
【解决方案2】:

在您的程序中,您需要添加一个检查 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 2021-02-14
    相关资源
    最近更新 更多