逻辑与运算符
我对逻辑 AND 运算符有点困惑。 我有这两行代码。这里num
和j
都是int。我遇到的情况是两个条件都满足,但我不知道为什么它不打印 j
的值。有人能指出其中的错误吗?提前致谢。
if(k==1 && num%j==0)
printf("%d",j);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
用简单的英语来说,表达式
k == 1 && num % j == 0
为真当且仅当k
等于 1 除num< 所得的余数/code> by
j
是 0。我不能说更多了。In plain English, the expression
k == 1 && num % j == 0
is true if and only ifk
equals 1 and the remainder from dividingnum
byj
is 0. Not much more I can say.这里有两种可能性。要么您永远无法到达 printf,要么您永远无法获得输出。
对于第一种情况,您确定 k == 1 和 num % j == 0 吗?向我们提供测试中的实际数值可能会有所帮助。请注意,如果
k
是一个浮点数(即计算结果),则它可能与 1.0 略有偏差,并且条件将返回 false。对于第二种情况,你是如何测试的?这应该打印出
j
的值,但它不会刷新输出,因此如果程序异常终止或控制台在程序结束时消失或您可能看不到它。尝试printf("%d\n", j);
甚至fflush(stdout);
以确保输出在控制台或终端上可见。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
andnum % j == 0
? Giving us the actual numeric values values in your test might help. Note that ifk
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. Tryprintf("%d\n", j);
or evenfflush(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.
您可能还想添加 else 语句。我已经数不清这样的事在我身上发生过多少次了。至少在编码的初始阶段这是一个很好的做法。这样做:
这将帮助您发现问题
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
您的代码运行良好,看看这个 测试用例:
http://ideone.com/1gz8R
所以问题不在于这两行。尝试在进入这些行之前打印涉及的三个值,您可能会对所看到的(或没有看到的)感到惊讶。
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).
在我看来,你还应该养成充分使用括号的习惯:
至少是这样。
You should also get in the habit of using parentheses liberally, imo:
at the least.