1. if语句结构如下
if(表达式)
语句1;
表达式为真,执行语句,否则跳过。
2. if..else.. 语句结构如下
if(表达式)
语句1;
else
语句2;
表达式为真,执行语句1,否则执行语句2。
小例子:判断最大值
#include <stdio.h>
int main(int argc, char* argv[])
{
int a = 5;
int b = 10;
int c = 15;
int max = 0;
if(a>b){
max=a;
}else{
max=b;
}
if(max<c){
max=c;
}
printf("max=%d\n",max);
return 0;
}
3.if...else if...语句的结构如下:
if(表达式1)
语句1;
else if(表达式2)
语句2;
else if(表达式3)
语句3;
…
else
语句n;
小例子:计算工资税额
#include <stdio.h>
int main(int argc, char* argv[])
{
int salary = 0;
float ratio = 0.0;
printf("please input your salary:");
scanf("%d",&salary);
if(salary > 50000)
ratio = 0.5;
else if(salary > 10000)
ratio = 0.3;
else if(salary > 7000)
ratio = 0.2;
else if(salary > 5000)
ratio = 0.1;
else
ratio = 0;
printf("the tax is %.2f\n",salary * ratio);
return 0;
}
4.switch语句的格式如下:
switch(表达式)
{
case 常量表达式1:
语句1;
break;
case 常量表达式2:
语句2;
break;
小例子:
#include <stdio.h>
int main(int argc, char* argv[])
{
char grade;
printf("please input grade");
scanf("%c",&grade);
switch(grade)
{
case 'A':
printf("成绩优秀\n");
break;
case 'B':
printf("成绩良好\n");
break;
case 'C':
printf("成绩有些差\n");
break;
}
return 0;
}