4. 不乱用if语句
有些人很喜欢用“if”语句,如下:
if(a == 0)
{
a++;
return(a);
}
if(a == 1)
{
a += 5;
return(a);
}
if(a == 2)
{
a += 10;
return(a);
}
if(a == 3)
{
a += 20;
return(a);
}
if(a == 4)
exit(1);
有没有比这更好的办法呢?else if语句?不是。好的方法是用“switch-case”语句来写简便的程序:
switch(a)
{
case 0: a++;
return(a);
case 1: a += 5;
return(a);
case 2: a += 10;
return(a);
case 3: a += 20;
return(a);
default: exit(1);
}
如果没有与a一致的值,会执行default里定义的作业,上面的例子是要执行结束。
有些人很喜欢用“if”语句,如下:
if(a == 0)
{
a++;
return(a);
}
if(a == 1)
{
a += 5;
return(a);
}
if(a == 2)
{
a += 10;
return(a);
}
if(a == 3)
{
a += 20;
return(a);
}
if(a == 4)
exit(1);
有没有比这更好的办法呢?else if语句?不是。好的方法是用“switch-case”语句来写简便的程序:
switch(a)
{
case 0: a++;
return(a);
case 1: a += 5;
return(a);
case 2: a += 10;
return(a);
case 3: a += 20;
return(a);
default: exit(1);
}
如果没有与a一致的值,会执行default里定义的作业,上面的例子是要执行结束。
Trackback: http://tb.blog.youkuaiyun.com/TrackBack.aspx?PostId=5701
本文探讨了在编程中如何更高效地使用条件语句。通过对比多个if语句与switch-case语句,展示了后者在代码简洁性和可读性方面的优势。

6644

被折叠的 条评论
为什么被折叠?



