if 语句中哪个条件为真
假设我有一个 if
语句,
if(condition1 || condition2 || condition3)
{
//do something
}
当我们进入循环时,是否可以找出 3 个条件中哪一个为真?
say I have an if
statement as such
if(condition1 || condition2 || condition3)
{
//do something
}
Is it possible to find out which of the 3 conditions was true when we enter the loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是的,您可以使用以下方法单独检查每个条件:
当然假设条件在过渡期间不太可能发生变化(例如线程、中断或内存映射 I/O)。
Yes, you can check each one individually with something like:
assuming of course that the conditions aren't likely to change in the interim (such as with threading, interrupts or memory-mapped I/O, for example).
不,您必须执行以下操作:
{
}
No. You'll have to do something like:
{
}
通过使用另一个 if 查询每个条件,有效地渲染第一个 if 无用,可以找出哪个条件为真。
It is possible to find out which of the conditions was true by querying each of them using another if, effectively rendering the first if useless.
一个简单的方法。
或者,如果您知道只有一个条件为真,请考虑使用
switch
。A simple method.
Or if you know that only one of the conditions is going to be true, consider using a
switch
.在调用 if 语句之前,您可以调用:
来查明哪个条件为真。
如果您想让程序根据条件表现不同,您需要将该代码放在单独的 if 语句中。
Before you call the if statement, you can call:
to find out which of the conditions was true.
If you would like to make the program behave differently according to the condition you will need to put that code in a separate if statement.
不可以。但是您可以通过以下方式实现:
我。在 3 个 or 条件内使用单独的 if else
或者
二.将三个或条件分成单独的对以找出匹配值
No. However you can achieve by:
i. Using seperate if else within the 3 or conditions
or
ii. break the three or conditions in separate pairs to find out matching value
你有短路操作员。 ||和&&。
例如,假设您有条件
if( x && y || z)
If x && y 的计算结果不为 true,则 y 和 z 永远不会进行比较。然而,如果 X 和 Y 为真,那么它将测试 y 或 z。在这种情况下,您的真实值来自 x 和 y 为真,且 y 或 z 为真这一事实。
You have the short circuit operators. || and &&.
So say for instance you have the condition,
if( x && y || z)
If x && y doesnt evaluate to true, then y and z are never compared. However if X and Y are true, then it will test y or z. In this case your true value comes from the fact that x and y is true, and y or z is true.