Logical AND operator

穿精又带淫゛_ 提交于 2019-12-24 08:53:17

问题


I am little confused with logical AND operator. I have these 2 lines of code. Here num and j are both 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. Can anybody point out the mistakes? Thanks in advance.

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

回答1:


In plain English, the expression k == 1 && num % j == 0 is true if and only if k equals 1 and the remainder from dividing num by j is 0. Not much more I can say.




回答2:


There's two possibilities here. Either you never get to the printf, or the output never gets to you.

For the first case, are you sure that k == 1 and 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.

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. Try printf("%d\n", j); or even fflush(stdout); to make sure the output is visible on your console or terminal.




回答3:


If conditions are true, there is no problem in your code.

Check the output here.




回答4:


you might also want to add an else statement. 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));
} 



回答5:


Your code runs fine, take a look at this testcase:

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).




回答6:


You should also get in the habit of using parentheses liberally, imo:

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

at the least.



来源:https://stackoverflow.com/questions/3496214/logical-and-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!