加入更多{} 为了风格一致以及扩展方便、少出错误,某些程序加入了大量}! if (i>j){ if (i>k){ max i; else max k; } else if (j>k){ max j; else max k; } } 11/68
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 加入更多 {} 为了风格一致以及扩展方便、少出错误,某些程序加入了大量 {}! if (i > j) { if (i > k) { max = i; } else { max = k; } } else { if (j > k) { max = j; } else { max = k; } } 11 / 68
级联(Cascaded)if语句 ●f语句支持级联使用,做系列条件测试 ·原始代码: if (n <0) printf("n is less than oIn"); else if (n ==0) printf("n is equal to oIn"); else printf("n is greater than oln"); 12/68
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 级联 (Cascaded ) if 语句 if 语句支持级联使用,做系列条件测试 原始代码: if (n < 0) printf("n i s less than 0\n"); else if (n == 0) printf("n i s equal to 0\n"); else printf("n i s greater than 0\n"); 12 / 68
级联(Cascaded)if语句(续) ·一般更倾向于如下的级联f语句写法 if (n <0) printf("n is less than oIn"); else if (n ==0) printf("n is equal to oIn"); else printf("n is greater than oln"); 13/68
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 级联 (Cascaded ) if 语句 (续) 一般更倾向于如下的级联 if 语句写法 if (n < 0) printf("n i s less than 0\n"); else if (n == 0) printf("n i s equal to 0\n"); else printf("n i s greater than 0\n"); 13 / 68
f语句级联的优点 当测试条件分支比较多时,级联的写法避免了过度的代码缩 进 if expression statement else if expression statement else if expression statement else statement 14/68
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . if 语句级联的优点 当测试条件分支比较多时,级联的写法避免了过度的代码缩 进 if ( expression ) statement else if ( expression ) statement ... else if ( expression ) statement else statement 14 / 68
f语句示例 计算分级所得税 1 #include <stdio.h> 2 int main(void){ 3 float tax,income; 4 printf("Enter value of income:") 5 scanf ("%f",&income) 6 if (income 2000.00f) 7 tax =.10f income; 8 else if (income 3000.00f) 9 tax .15f income; 10 else if (income 5000.00f) 11 tax =.20f income; else if (income 10000.00f) 13 tax =.30f income; 14 else 15 tax =.40f income; 16 if(tax<100.00f) 17 tax=100.00f; 18 printf("Tax:$%.2fIn",tax); 19 return 0; 15/68
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . if 语句示例 —— 计算分级所得税 1 #include <stdio.h> 2 int main(void) { 3 float tax, income; 4 printf("Enter value of income: "); 5 scanf("%f ", &income); 6 if (income < 2000.00f) 7 tax = .10f * income; 8 else if (income < 3000.00f) 9 tax = .15f * income; 10 else if (income < 5000.00f) 11 tax = .20f * income; 12 else if (income < 10000.00f) 13 tax = .30f * income; 14 else 15 tax = .40f * income; 16 if (tax < 100.00f) 17 tax = 100.00f; 18 printf("Tax: $%.2f \n", tax); 19 return 0; 20 } 15 / 68