一、if else语句
C语言中由一个分号;隔开的就是一条语句。
C语言中,用各种操作符把变量连起来的有意义的式子,就叫做表达式。
if语句的执行过程:
1.先执行()中的表达式,得到真假结果
2.条件判定功能
3.进行分支功能
注释代码:
IF(0)
{}//不推荐
#include <stdio.h>
int main()
{
if(0)
{
printf("hello world\n");//不打印
}
return 0;
C语言当中0为假,非0为真(1是其中一种情况)
进行if语句条件判断时,一般可以写作if(值 == 变量),便于查错。
else会与最近的未匹配的的if进行匹配,与放置的位置无关
#include <stdio.h>
int main()
{
int x = 3;
if(x > 0)
{
printf("hello world\n");
if(x==1)//1
{
if(x==2)//2
{
printf("hello\n");
}
}
else(x==2)//只匹配1
{
printf("world\n");
}
}
return 0;
一、switch case 语句
示例:swtich case语句
#include <stdio.h>
#include <windows.h>
#pragma warning (disable:4996)
int main()
{
int day = 0;
printf("Please Enter Your Day#");
scanf("%d", &day);
switch (day)//switch(整形\整形表达式)
{
case 1://case本身是用来判定功能的
printf("星期1\n");
break; //用来进行分支功能,可以跳出switch语句
case 2:
printf("星期2\n");
break;//
case 3:
printf("星期3\n");
break;
case 4:
printf("星期4\n");
break;
case 5:
printf("星期5\n");
break;
case 6:
printf("星期6\n");
break;
case 7:
printf("星期天\n");
break;
default: //default位置不影响switch case语句结构
printf("你输入的日期有误,请重新输入!");
break;
}
system("pause");
return 0;
}
#include <stdio.h>
#include <windows.h>
void show()
{
int a = 10;
printf("%d\n", a);
}
int main()
{
int day = 0;
int quit = 0;
while (!quit)
{
scanf("%d", &day);
switch (day)
//switch(day == 1)//不推荐
{
//多种情况对应同一结果可以省略break
case 1:
case 2:
case 3:
case 4:
case 5:
//不能直接在case后创建临时变量,需用{}\封装成函数
//int a = 0;
show();
printf("周内\n");
//break;
//return;//需要退出while循环;switch case程序中一般不使用return
quit = 1;
break;
case 6:
case 7:
printf("周末\n");
break;
default:
printf("你输入的日期有误,请重新输入!");
break;
}
}
return 0;
}
1、每个case语句的结尾一般要加上break;否则会导致多个分支输出同一结果
(多个分支同一结果时可以省略)。
2、在case语句中不能直接定义局部变量,需要使用代码块\封装成函数
3、在switch()中不建议使用bool类型,即swittch(x == 1)
4、需要退出while循环;switch case程序中一般不使用return,可定义状态变量
5、default可以放在switch任意位置(case-break之外,与case并列),不影响
switch case语句结构,建议放在语句末尾。
6、不要为了使用switch语句而特意取创建变量
二、do、while、for关键字
1.引入
代码如下(示例):
#include <stdio.h>
#include <windows.h>
int main()
{
int count = 10;//循环条件初始化
do
{
printf("count = %d\n", count);
count--;
} while (count>0);//循环条件更新,至少循环一次,注意分号
//for
for (int i = 0; i < 10; i++)
{
printf("count = %d\n", i);
}
//while
//int count = 10;//循环条件初始化
while (count>0)
{
//循环体
printf("%d\n", count);
printf("%d\n", count);
printf("%d\n", count);
count--;//循环条件更新
}
system("pause");
return 0;
}
int main()
{
//do while死循环
do
{
;
} while (1);
//for死循环
for (;;)
{
;
}
//while死循环
while (1)
{
;
}
}
2.getchar
int getchar(void)
为什么getchar的返回类型时int,而不是其他类型
这是因为getchar接收的是字符,[0,255]时是ASCLL码,是合法范围,但超过255,如1 0000 0000时便不合法,所以是int类型。
键盘输入的内容或者是显示器打印的内容,都是字符。
代码如下(示例):
#include <stdio.h>
#include <windows.h>
int main()
{
while (1)
{
int c = getchar();//同样接收\n
if (c == '#')
{
break;
}
printf("%c", c);
}
printf("while end...\n");
system("pause");
return 0;
}