int a =10;if(a >5){printf("a is greater than 5\n");}
扩展形式:
if (表达式) 语句1; else 语句2;:当表达式为真时执行语句1,否则执行语句2。
多分支结构:使用多个 else if 来处理多种条件。
扩展形式示例:
int a =10;if(a >15){printf("a is greater than 15\n");}elseif(a >10){printf("a is greater than 10 but less than or equal to 15\n");}else{printf("a is less than or equal to 10\n");}
表达式详解:
表达式可以是关系表达式、逻辑表达式或直接是数值。
解释如何构造有效的判断条件。
复合语句的使用:
使用花括号 {} 包围的语句块以在条件为真时执行多个语句。
3. 关系与逻辑运算符
关系运算符:
<, <=, >, >=, ==, !=:用于比较两个值,结果为真或假。
优先级及其与算术运算符的关系。
关系运算符示例:
int a =10, b =20;if(a == b){printf("a is equal to b\n");}elseif(a < b){printf("a is less than b\n");}
逻辑运算符:
&& (与), || (或), ! (非):用于组合多个关系表达式。
逻辑运算符示例:
int a =10, b =5, c =20;if(a > b && a < c){printf("a is between b and c\n");}
int num =2;switch(num){case1:printf("Number is 1\n");break;case2:printf("Number is 2\n");break;default:printf("Number is neither 1 nor 2\n");}
6. 选择结构的嵌套
嵌套if结构:
在if语句中又包含一个或多个if语句称为if语句的嵌套
嵌套if结构示例:
int a =10, b =20;if(a >5){if(b >15){printf("Both a and b are greater than their respective conditions\n");}}
7. 实战编程示例
综合示例:
#include<stdio.h>intmain(){int age =20;if(age <18){printf("You are a minor.\n");}elseif(age >=18&& age <60){printf("You are an adult.\n");}else{printf("You are a senior citizen.\n");}int num1 =10, num2 =20, num3 =30;int max =(num1 > num2)?(num1 > num3 ? num1 : num3):(num2 > num3 ? num2 : num3);printf("The maximum number is %d\n", max);return0;}