if-else-if梯形图的两个部分中的条件语句为true [英] Conditional statement true in both parts of if-else-if ladder

查看:338
本文介绍了if-else-if梯形图的两个部分中的条件语句为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您具有这样的代码:

If you have code like this:

if (A > X && B > Y)
{
   Action1();
}
else if(A > X || B > Y)
{
   Action2();
}

带有 A> X B> Y ,是否会执行 if-else-if 阶梯的两个部分?

With A > X and B > Y, will both parts of the if-else-if ladder be executed?

我正在处理存在此问题的Java代码。我通常使用C ++进行工作,但是是使用这两种语言编写的非常新的(和零星的)程序员。

I'm dealing with Java code where this is present. I normally work in C++, but am an extremely new (and sporadic) programmer in both languages.

推荐答案

不,他们不会两者都执行。顺序取决于您的编写方式,从逻辑上讲这很有意义;即使第二个读为 else if,您仍然可以将其视为 else。

No, they won't both execute. It goes in order of how you've written them, and logically this makes sense; Even though the second one reads 'else if', you can still think of it as 'else'.

考虑一个典型的if / else块:

Consider a typical if/else block:

if(true){
   // Blah
} else{
   // Blah blah
}

如果您的第一句话是正确的,那么您甚至不必费心查看需要做什么在其他情况下,因为它无关紧要。同样,如果您使用的是 if / elseif,则不会浪费时间查看后续块,因为第一个是正确的。

If your first statement is true, you don't even bother looking at what needs to be done in the else case, because it is irrelevant. Similarly, if you have 'if/elseif', you won't waste your time looking at succeeding blocks because the first one is true.

一个现实的例子可能是分配成绩。您可以尝试以下操作:

A real world example could be assigning grades. You might try something like this:

if(grade > 90){
   // Student gets A
} else if(grade > 80){
   // Student gets B
} else if(grade > 70){
   // Student gets c
}

如果学生获得99%,则所有这些条件都是正确的。但是,您不会分配学生A,B和C。

If the student got a 99%, all of these conditions are true. However, you're not going to assign the student A, B and C.

这就是为什么订单很重要的原因。如果我执行此代码,并将B块放在A块之前,则将为该同一学生分配B而不是A,因为不会执行A块。

That's why order is important. If I executed this code, and put the B block before the A block, you would assign that same student with a B instead of an A, because the A block wouldn't be executed.

这篇关于if-else-if梯形图的两个部分中的条件语句为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆