在一开始if
之后,作为很多else if
和许多if
的示例。我在下面添加了一些伪代码。
if (x=1)
print x;
if (x=2)
print x;
if (x=3)
print x;
或者
if (x=1)
print x;
else if (x=2)
print x;
else if (x=3)
print x;
答案 0 :(得分:4)
你的代码不会编译;如果您确实想检查条件,则需要使用==
代替=
;不仅仅是效率,这两种技术的使用取决于要求。您可以将第一种情况用于以下场景:
if (x==1)
//Do something
// 'x' may change here
if (x==2) // check for next condition
// Do another thing
// 'x' may change
if (x==3) // check for another condition
// Do something more
//'x' may change
如果x
的值没有变化,您可以执行第二组代码。因此,一旦找到真实条件,您就可以跳过评估其余条件。考虑x=1
因此,它不会检查x==2
和x==3
,以便我们可以缩短执行时间。
x=1;
if (x==1) // Evaluates to true;
// Do Something
// Exit the if
else if (x==2) // will not check for this
//Do another thing
else if (x==3) // will not check for this
//Do another thing
如果您有更多要检查的条目,则应使用switch代替这两项。
答案 1 :(得分:2)
使用“if else”更有效,因为如果条件为真,则不会检查其他“if”。但是在你的第一个结构中,无论哪个“如果”仍然检查所有其他if语句都无关紧要。
答案 2 :(得分:1)
效率实际上取决于您运行的编译器/编译器版本。但除非你做成千上万的,否则性能不会真的受到影响。如果条件为真,我会使用if else,其余的if语句不需要运行
答案 3 :(得分:1)
两者都很有效,两者都有不同的用途。
使用If else if
。例如,如果要求或问题是查找数字是奇数还是偶数:
$num = 0
if($num == 0)
// print 'neutral'
else if($num % 2 == 0)
// print even
else
// print odd
输出:
neutral
正如您在上面的示例中所看到的,如果一个条件满足,我们不需要将它与其他条件进行比较,因为我们已经有了答案,它的浪费资源并且如果我们这样做会产生不正确的结果< /强>:
$num = 0
if($num == 0)
// print neutral
if($num % 2 == 0)
// print even
if($num % 2 != 0)
// print odd
输出:
neutral
even
使用Ifs
。另一个现实生活中的例子可能是,如果您要比较3个数字并检查哪个数字最大:
$num1 = 2
$num2 = 30
$num3 = 31
$large = $num1
if($num2 > $large)
$large = $num2
if($num3 > $large)
$large = $num3
输出:
largest is $num3 or 31
正如您在上面的示例中所看到的,我们需要比较数字的所有以获得最大值。如果我们这样做,我们将得出不正确的结果:
$num1 = 2
$num2 = 30
$num3 = 31
$large = $num1
if($num2 > $large)
$large = $num2
else if($num3 > $large)
$large = $num3
输出:
largest is $num2 or 30
答案 4 :(得分:1)
在大多数情况下,在if-if-if语句上使用if-elseif-else和switch语句效率更高,因为它使编译器更容易创建跳转/查找表。这也是更好的做法,因为它使您的代码更具可读性,并且编译器确保您在开关中包括默认大小写。该答案以及比较这三种不同陈述的this table都是使用此页面上的其他答案以及类似的question的答案合成的。
答案 5 :(得分:0)
更好 - 使用switch case:
int x = 3;
switch (x)
{
case 1:
print "1";
break;
case 2:
print "2";
break;
case 3:
print "3";
break;
default:
print "something else";
break;
}