首页 > 解决方案 > 我尝试编写一个使用函数查找 GCD 的程序。为什么这段代码不起作用?

问题描述

这是我到目前为止写的代码,我找不到任何逻辑冗余。请帮忙。

#include<stdio.h>   

int gcd(int,int);  
void main()

{
int a, b, c;
printf("enter 2 num\n" );
scanf("%d%d",&a,&b);  
printf("gcd of %d and %d is %d",a,b,gcd(a,b));
}

int gcd(int a,int b)  
{
int i, c;
for(i=0;i<a&&i<b;i++)
{
    if((a%i==0)&&(b%i==0))
        
    c=i;
    
}
return c;

}

我没有得到任何输出。输入:25、75

附言。我的第一个问题

编辑:感谢您的帮助,我犯了一个愚蠢的错误并初始化了 i=0,所以我的程序崩溃了。

标签: cfunction

解决方案


除非我的假设是错误的,否则您使用的功能是错误的。你能指定你为函数使用的算法吗?如果您愿意,可以参考下面附加的基于欧几里德 GCD 算法的函数。

int euclid(int x, int y)
{
    if (y == 0) {
     return x;
    } else if (x >= y && y > 0) {
       return euclid(y, (x % y));
  } 
}  

完整计划:

#include <stdio.h>
#include <time.h>
int euclid(int, int);
int main()
{
  int m, n, gcd;
  clock_t start,end;
  double cpu_time_used; 
  printf("\nEnter two numbers to find gcd using Euclidean algorithm: ");
  scanf("%d%d", &m, &n);
  start=clock(); 
  gcd = euclid(m,n);
  end=clock();
  cpu_time_used=((double) (end-start)) / CLOCKS_PER_SEC;
  if (gcd){
    printf("\nThe GCD of %d and %d is %d", m, n, gcd);
    printf("\nGCD Function took %lf Seconds to Execute\n\n",cpu_time_used);
  }
  else
    printf("\nInvalid input\n");
  return 0;
 }


int euclid(int x, int y)
{
  if (y == 0) {
      return x;
  } else if (x >= y && y > 0) {
      return euclid(y, (x % y));
  }
 }

推荐阅读