关于if/else 选择结构的一点认识

来源:互联网 发布:2016windows平板有哪些 编辑:程序博客网 时间:2024/05/22 14:54


这个是我以前忽视的一个小问题,是嵌套if/else结构,测试多个选择,将一个if/else选择放在另一个if/else选择中。例如:

(伪代码)

If student's grade is greater than or equal to 90

Print"A"

else

If student's grade is greater than or equal to 80

Print"B"

        else

         If student's grade is greater than or equal to 70

Print"C"

else

If student's grade is greater than or equal to 60

Print"D"

else

Print"F"



那这段代码对应的C++代码:

if (grade >= 90)

cout << "A";

else

if(grade >= 80)

cout << "B";

else

if(grade >= 70)

cout << "C";

else

if(grade >= 60)

cout << "D";

else

cout << "F";



那么这段可以写成这样:

if (grade >= 90)

cout << "A";

else if(grade >= 80)

cout << "B";

else if(grade >= 70)

cout << "C";

else if(grade >= 60)

cout << "D";

else

cout << "F";


这两种形式是等价的,后边的这段代码更常用,可以避免深层缩排使代码移到右边。

注意点是在嵌套IF/ELSE结构中,测试条件中true可能性较大的应放在嵌套IF/ELSE结构开头,从而使嵌套IF/ELSE结构运行得更快,比测试不常发生的情况能更早退出。


原创粉丝点击