[英]&& condition working as || in do while loop in c
The AND
( &&
) condition evaluates as OR
( ||
) in this code. AND
( &&
)条件在此代码中计算为OR
( ||
)。 For ex., when user inputs numbers 6 and 7 , the output is 12 but when the I replace &&
with ||
例如,当用户输入数字6和7时 ,输出为12但是当我用||
替换&&
时 the output is 42 . 输出是42 。
#include<stdio.h>
int main()
{
int a,b,max,lcm;
printf("Enter 2 numbers: ");
scanf("%d %d", &a, &b);
if(a>b)
{
max=a;
}
else
{
max=b;
}
do
{
max++;
} while(max%a!=0 && max%b!=0);
lcm=max;
printf("LCM of %d and %d is %d\n", a,b,lcm);
return 0;
}
No, the &&
condition is working as an and
condition, just as it should. 不, &&
条件正如它应该的那样起作用and
条件。 When you input 6
and 7
, max%a
evaluates to 0
when max
is 12
. 输入6
和7
,当max
为12
时, max%a
计算结果为0
。 At that point max%a != 0
evaluates to false
( false && true == false
), and max%a != 0 && max%b != 0
evaluates to false
, and your loop exits. 此时, max%a != 0
计算结果为false
( false && true == false
), max%a != 0 && max%b != 0
计算结果为false
,并且循环退出。 However, max%a != 0 || max%b != 0
但是, max%a != 0 || max%b != 0
max%a != 0 || max%b != 0
evaluates to true
( max%b
is 5
for a max
of 12
and b
of 7
, false || true == true
), so the loop continues. max%a != 0 || max%b != 0
计算结果为true
( max%b
为5
, max
为12
, b
为7
, false || true == true
),因此循环继续。
I would change the do {..} while (...);
我会改变do {..} while (...);
loop to: 循环到:
while (1)
{
max++;
if ( max%a == 0 && max%b == 0 )
{
break;
}
}
It is so much easier to follow, at least for me. 至少对我来说,这更容易理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.