简体   繁体   English

逻辑AND运算子

[英]Logical AND operator

I am little confused with logical AND operator. 我对逻辑AND运算符有点困惑。 I have these 2 lines of code. 我有这两行代码。 Here num and j are both int. 这里numj都是int。 I have a situation where both the conditions are satisfied, but I don't know why it's not printing the value of j . 我遇到了两个条件都满足的情况,但是我不知道为什么它没有打印j的值。 Can anybody point out the mistakes? 有人可以指出错误吗? Thanks in advance. 提前致谢。

if(k==1 && num%j==0)
    printf("%d",j);

用简单的英语来说,当且仅当k等于1 num除以j的余数为0时,表达式k == 1 && num % j == 0才是正确的。

There's two possibilities here. 这里有两种可能性。 Either you never get to the printf , or the output never gets to you. 要么您永远不会进入printf ,要么输出永远不会到达您。

For the first case, are you sure that k == 1 and num % j == 0 ? 对于第一种情况,您确定k == 1并且num % j == 0吗? Giving us the actual numeric values values in your test might help. 在测试中提供实际的数值可能会有所帮助。 Note that if k is a floating-point number that's the result of a computation it might be very slightly off from 1.0, and the condition would return false. 请注意,如果k是计算结果的浮点数,则可能与1.0略有出入,条件将返回false。

For the second case, how are you testing this? 对于第二种情况,您如何测试呢? That should print out the value of j , but it doesn't flush the output, so if the program terminates abnormally or the console goes away at the end of the program or something you may not see it. 那应该打印出j的值,但是不会刷新输出,因此,如果程序异常终止或控制台在程序末尾消失,或者您可能看不到它。 Try printf("%d\\n", j); 尝试printf("%d\\n", j); or even fflush(stdout); 甚至fflush(stdout); to make sure the output is visible on your console or terminal. 确保输出在控制台或终端上可见。

If conditions are true, there is no problem in your code. 如果条件为真,则代码中没有问题。

Check the output here . 此处检查输出。

you might also want to add an else statement. 您可能还想添加else语句。 I cant count how many times this has happened to me. 我无法数出这种情况发生在我身上的次数。 it is a good practice at least when in the initial stages of you coding. 至少在编码初期,这是一个好习惯。 do this: 做这个:

this will help you catch the problem 这将帮助您发现问题

if(k==1 && num%j==0)
    printf("%d",j);
else {
   printf("%d \n",k);
   printf("%d \n",num);
   printf("%d \n",j);
   printf("%d \n",(num%j));
} 

Your code runs fine, take a look at this testcase: 您的代码运行良好,请看以下测试用例:

http://ideone.com/1gz8R http://ideone.com/1gz8R

So the problem is not with those two lines. 因此,问题不在于这两行。 Try printing the three values involved right before you get into those lines, you may be surprised by what you see (or don't see). 在进入这些行之前,尝试打印涉及的三个值,您可能会对所看到的(或看不到的)感到惊讶。

You should also get in the habit of using parentheses liberally, imo: 您还应该养成自由使用括号的习惯,imo:

if(k == 1 && (num % j == 0))

at the least. 至少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM