c - 我尝试编写一个使用函数查找 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,所以我的程序崩溃了。
解决方案
除非我的假设是错误的,否则您使用的功能是错误的。你能指定你为函数使用的算法吗?如果您愿意,可以参考下面附加的基于欧几里德 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));
}
}
推荐阅读
- c# - 根据 ID 选择文件
- php - 通过子目录中的 htaccess 从 URL 中删除目录名称
- javascript - 在 NodeJS 中返回未定义的异步函数
- postgresql - docker-compose 在运行命令时找不到要注入 Postgresql 的文件
- c++ - SCIP 求解器中的 SCIPgetSolVal 未返回解值
- android - 新片段下可见的先前活动
- python - 如何在烧瓶中使用 HTTPS 运行 localhost?
- javascript - 为什么 vue-cli-3 不会构建,“找不到'wepack'”?
- python - 我应该如何将 2 个参数从我的列表中传递给 csv-writer?
- bash - 如何找到一个数字序列