1. if 语句的语法格式
if(条件)
{
语句1;
语句2;
语句...
}
2. if-else 语法格式
① if 和 else 的连连看
else的匹配采用就近原则,离上方哪个 if 最近,就属于哪个 if
② { } 内的语句只有一条的时候, { } 可以省略
③ 句法格式
if(关系表达式) //这里不加分号,话说一半天打雷劈
{
语句;
语句;
...
}
else
{
语句;
语句;
...
}
3. if-else语句的“嵌套”
——题目另解:在三个数中找出最大的一个数
if 语句 | if-else 语句 |
if (a>=b && a>=c) printf("%d",c); | if (a>=b) //条件① { if (a>=c) //条件② { printf("%d",a) } } |
当a>=b条件满足时,再进一步讨论a与c的关系 (如果a>=c也成立的话,就打印a) |
#include<stdio.h>
int main()
{
int a,b,c;
printf("请输入想比较的三个数字\n");
scanf("%d%d%d",&a,&b,&c);
if (a>=b)
if(a>=c)
printf("%d",a);
else
printf("%d",c);
else
if(b>=c)
printf("%d",b);
else
printf("%d",c);
return 0;
}
4. 输入一个年号,判断是否为闰年,如果是则输出“Yes”,否则输出“No”。
只要满足下列两个条件之一者,即是闰年
(1) 年号能被4整除,但要排除同时能被100整除;
(2) 年号能被400整除。
如何表示这个条件?假设输入年号赋值给变量y
(y%4= =0 && y%100!=0) || (y%400= =0)
#include <stdio.h>
main()
{
int y;
printf("输入一个年号:");
scanf("%d",&y);
if ((y%4= =0 && y%100!=0) || (y%400= =0))
printf("Yes");
else
printf("No");
printf("\n程序运行结束。");
}
5. 输入一个实数x,如果2.0<=x<=6.0,则整数y=1;否则,y=0
#include <stdio.h>
main()
{
float x;
int y;
printf("Please input x:");
scanf("%f",&x);
if(x>=2.0&&x<=6.0)
y=1;
else
y=0;
printf("y=%d\n",y);
}
6. 处理学生的某一门课程考试成绩,要求为成绩不及格的学生打印补考通知单,而为成绩及格的学生打印课程成绩单。
#include <stdio.h>
main()
{ float score;
printf("\n 请输入一位学生的成绩:");
scanf("%f",&score);
if (score<60)
{ printf("\n 成绩为 %4.1f \n",score);
printf("\n 请于下周五18:30在二教302室参加补考. \n");
}
else
printf("\n 成绩为 %4.1f,该门课程已通过. \n",score);
}
7. 输入学生的百分制比成绩score,按分数输出其等级
score≥90 为 Excellent,
80≤ score < 90 为 Good,
70≤ score < 80 为 Right,
60≤ score< 70 为 Pass,
score<60 为Failed。
#include<stdio.h>
main()
{ float score;
printf("Input score(0~100):");
scanf("%f",&score);
if(score>=90)
printf("Excellent!");
else if(score>=80)
printf("Good!");
else if(score>=70)
printf("Right!");
else if(score>=60)
printf("Pass!");
else
printf("Failed!");
}