嵌套 if() ... else VS if() .. else Ladder
与 if()...else 梯形图相比,嵌套的 if()...else 语句需要更多的执行时间(它们更慢),因为嵌套的 if()...else 语句在满足外部条件 if() 语句时检查所有内部条件语句,而 if()..else 梯形图将在任何一个时间点停止条件测试 if() 或 else if() 条件语句为真。
一个 if()...else 阶梯:
#include <stdio.h>
int main(int argc, char *argv[])
{
int a, b, c;
printf("\nEnter Three numbers = ");
scanf("%d%d%d", &a, &b, &c);
if ((a < b) && (a < c))
{
printf("\na = %d is the smallest.", a);
}
else if ((b < a) && (b < c))
{
printf("\nb = %d is the smallest.", b);
}
else if ((c < a) && (c < b))
{
printf("\nc = %d is the smallest.", c);
}
else
{
printf("\nImprove your coding logic");
}
return 0;
}
在一般情况下,被认为比同等的嵌套 if()...else 更好:
#include <stdio.h>
int main(int argc, char *argv[])
{
int a, b, c;
printf("\nEnter Three numbers = ");
scanf("%d%d%d", &a, &b, &c);
if (a < b)
{
if (a < c)
{
printf("\na = %d is the smallest.", a);
}
else
{
printf("\nc = %d is the smallest.", c);
}
}
else
{
if(b < c)
{
printf("\nb = %d is the smallest.", b);
}
else
{
printf("\nc = %d is the smallest.", c);
}
}
return 0;
}