C语言简单程序:求2个数的最大公约数。看哪错了。

来源:百度知道 编辑:UC知道 时间:2024/05/25 15:06:28
#include <stdio.h>
main()
{int a,b,c,t;
scanf ("%d,%d",&a,&b);
t=a<b?a:b;
for(c=1;c<=t;c++)
{
if(a%c!=0&&b%c!=0)
printf("%d",c);
continue;
}
}

我给你改了,
你的if的意思是若c不能被a和b整除,则输出c。。。这c和公约数一点关系都没有

#include <stdio.h>
main()
{int a,b,c,t;
scanf ("%d,%d",&a,&b);
t=a<b?a:b;
for(c=t;c>0;c++)
{
if(a%c==0&&b%c==0)
printf("%d",c);
break;
}
}

#include <stdio.h>
main()
{int a,b,c,t;
scanf ("%d,%d",&a,&b);
t=a<b?a:b;
for(c=t;c>0;c--)
{ if(a%c==0&&b%c==0)
printf("%d",c); break;} }

你要最大公约数的话,for循环应该从大到小才对,
for(c=t;c>=1;--c)
还有就是找到就应该跳出循环吧,应该用break而不是continue
for(c=t;c>=1;--c)
{
if(a%c==0&&b%c==0) //余数为0才说明能被整除
{
printf("%d",c);
break; //找到就跳出吧
}
}

其实还有更快的做法
int a,b,r;
scanf ("%d,%d",&a,&b);
for(;b;r=a%b, a=b, b=r);
printf("%d", a);

#include <stdio.h>
void main()
{
int a,b,c,t,d;
s