[英]i am trying to write Euclidean Algorithm but program crash when i use loop in c code
I am trying to write the Euclidean Algorithm in C code. 我正在尝试用C代码编写欧几里得算法 。 When I use the
do while
or for
loop the program crashes: 当我使用
do while
或for
循环时,程序崩溃:
#include<stdio.h>
int gcd(int a,int b);
int main()
{
int x,r,y;
printf("Enter two values:\n");
scanf("%d%d",&x,&y);
if(x<y)r=x,x=y,y=r;
r=gcd(x,y);
printf("\n\n Result: %d",r);
return 0;
}
int gcd(int a,int b)
{
if(a==0||b==0)
{
if(a==0)return b;
if(b==0)return a;
}
else
{
for(;;a>0||b>0)//also try with do while loop but problem same
{
int x;
x=a%b;
a=b;
b=x;
}
}
}
Can you please explain me the reason behind the crash of the program? 您能否解释一下程序崩溃的原因? I use codeblocks with
gcc
我在
gcc
使用代码块
This: 这个:
for(;;a>0||b>0)
is an infinite loop, then end condition is the middle part, it should be: 是一个无限循环,那么结束条件是中间部分,它应该是:
for (; a > 0 || b > 0;)
I doubt the logic of that condition, shouldn't it be &&
? 我怀疑这种情况的逻辑,不是
&&
吗?
Instead of if(x<y)r=x,x=y,y=r;
代替
if(x<y)r=x,x=y,y=r;
you will need to do: 您将需要执行以下操作:
if(x < y){
r = x;
x = y;
y = r;
}
Also you will need to place condition in second statement of for
loop. 另外,您需要将条件放在
for
循环的第二条语句中。 Instead of: 代替:
for(;;a>0||b>0)
{
...
}
you could do while(a > 0 && b > 0)
. 你可以做
while(a > 0 && b > 0)
。 Depending on your familiarity you could use recursion like: 根据您的熟悉程度,您可以使用以下递归:
int hcf(int a, int b)
{
if (b == 0)
return a;
else
return hcf(b, a%b);
}
Also note that your hcf
function does not have return statement in else
block. 还要注意,您的
hcf
函数在else
块中没有return语句。 So you will have to use conditional return: 因此,您将必须使用条件返回:
if (a == 0) return b;
else return a;
at the end of hcf
function 在
hcf
函数的末尾
This statement 这个说法
for(;;a>0||b>0)
does nothing so you have an endless loop. 什么也没做,所以你有一个无限循环。
What seem to happen is that b
becomes zero and then you do a % 0
which is illegal and cause a crash. 似乎发生的事情是
b
变为零,然后执行a % 0
,这是非法的并导致崩溃。
Remember that it is the second statement in the for-loop that is the condition for terminating the loop - it's not the third. 请记住,是for循环中的第二条语句是终止循环的条件-不是第三条。 So maybe you wanted:
所以也许您想要:
for( ; a>0||b>0; )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.