数组名本身就是地址
判断2个字符串大小不能用“==”,strcmp函数是string compare(字符串比较)的缩写,用于比较两个字符串并根据比较结果返回整数。基本形式为strcmp(str1,str2),若str1=str2,则返回零;若str1<str2,则返回负数;若str1>str2,则返回正数。
一、if语句有关知识
if(条件)
语句;
1.if与else
#include <stdio.h>
int main()
{
int a = 0;
int b = 2;
if (a == 1)
if (b == 2)
printf("hehe\n");
else//与离得近的if语句匹配,注意排版
printf("haha\n");
return 0;
}
上述代码无执行结果,改正:
#include <stdio.h>
int main()
{
int a = 0;
int b = 2;
if (a == 1)
{
if (b == 2)
printf("hehe\n");
}
else
{
printf("haha\n");
}
return 0;
}
上述代码执行结果为:haha
2. if(判断书写格式)
int main()
{
int num = 1;
//if (num = 5)//此时的含义是把5赋值给num,结果为非0为真,执行 printf("hehe\n");
//if(5 = num)//这样写有报错效果
if(5==num)//最好的书写方式,常量与变量的比较
{
printf("hehe\n");
}
return 0;
}
二、switch(整形表达式)
#include<stdio.h>
//1,2,3,4,5 工作日
//6,7 休息日
int main()
{
int day = 0;
//输入
scanf("%d", &day);
switch (day)
{
//case 整形常量表达式:
case 1:
case 2:
case 3:
case 4:
case 5:
printf("工作日\n");
break;//如果没有break会继续往下走
case 6:
case 7:
printf("休息日\n");
break;
default:
printf("选择错误\n");
break;
}
return 0;
}
#include <stdio.h>
int main()
{
int n = 1;
int m = 2;
switch (n)
{
case 1:m++;//没有break继续执行
case 2:n++;
case 3:
switch (n)
{//switch允许嵌套使用
case 1:n++;
case 2:
m++;n++;
break;//只跳出自己的switch循环
}
case 4:
m++;
break;
default:
break;
}
printf("m = %d, n = %d\n", m, n);
return 0;
执行结果为m = 5, n = 3
三、while语句
while(表达式)
循环语句;
while中的break和continue
break直接终止循环
int main()
{
//使用while循环在屏幕上打印1~10
int i = 1;
while (i <= 10)
{
if (i == 5)
break;//直接终止循环
printf("%d ", i);
i++;
}
return 0;
}
continue终止本次循环,本次循环后面的代码不会执行,直接跳入下一次循环
int main()
{
//使用while循环在屏幕上打印1~10
int i = 1;
while (i <= 10)
{
if (i == 5)
continue;//跳过此次循环,i不再++
printf("%d ", i);
i++;
}
return 0;
}
1.getchar函数:
getchar函数是简单的一次读一个字符的函数,每次调用时从文本流中读入下一个字符,并将其作为结果值返回。值得注意的是,返回值是int类型即它返回的是字符的ASCII码。当程序调用getchar()时,程序就等着用户按键。用户输入的字符被存放在键盘缓冲区中,直到用户按回车为止。
通俗来说,getchar函数的作用是从键盘(缓冲区)读取用户的输入,返回读取到的字符的ASCII码值。