基本类型(整型,浮点型,字符型)
常量
整型 100 125 -100
实型 3.14 0.125 -3.12
字符型 'a' 'b' '2' 不能缺少单引号,有且只能有一个字母
字符串常量 “a” “avc”
变量
具有特定属性的一个储存单元
第一个字符必须为字母或下划线
不可以含有点或特殊符号
变量不可以于关键字同名
变量必须先定义,后使用
整型变量
符号常量
#include <stdio.h>
#define PI 3+2
int main() {
PI=28 (error:lvalue requierd as left operand of assignment ,左操作数必须为左值,左值必须是变量,但是现在PI 已经被定义了,不再属于变量)
int i=PI*2; //符号常量PI是直接替换的,最终结果为7
printf(_format:"i=%d\n",i);
printf(_format:"i size=%d\n",sizeof(i)); //sizeof可以用来计算某个变量的空间大小
//int变量占4个字节
return 0;
}
浮点型
小数形式,指数形式
注意:字母之前必须有数字,且后面的指数必须为整数
错误示例:e3 ,2.1e3.5,e
float浮点型占4个字节
#include <stdio.h>
int main() {
float f=3e-3;
printf(_format:"f=%f\n",f);
return 0;
}
字符型
字符型常量
\n 换行 (一个字符)
\\ 反斜杠
\b 退格
字符型变量(char)
字符占有一个字节
#include <stdio.h>
int main() {
char c='A';
printf(_format:"%c\n",c+32);//%c以字符形式输出,c+32:以大写字母形式输出
printf(_format:"%d\n",c); //%d以整形形式输出
字符串常量
' '字符型常量
" "字符串常量
字符串常量本身带有一个斜杠,所以自带一个字节
混合运算
类型强制转换场景
整型数进行除法运算时,如果运算结果为小数,那么储存浮点数时一定要进行强制类型转换
#include <stdio.h>
int main() {
int i=5;
float f=i/2; //这里做的是整型运算,因为左右操作数都是整型
float k=(float)i/2; //将整型变量进行转化,就可得到2.5
printf(_format:"%f\n",f);
printf(_format:"%f\n",k);
return 0;
}
结果:2.000000
printf函数
%c 字符
%d 带符号整数
%f 浮点数
%s 一串字符
%u 无符号整数
%x 无符号十六进制数,用小写字母
#include <stdio.h>
int main() {
int age=21; //int默认是带符号的,可以是整数,可以是负数,也可以是零
printf(_format:"hello %s,you are %d years old\n","Bob",age); //%s对应的是"Bob",一串字符 位置是一一对应的
return 0;
}
printf函数输出对齐
#include <stdio.h>
int main() {
int i=10;
float f=96.3;
printf(_format:"student number=%3d (3d代表它会占三格的位置,即使它的长度没有三个空格) score=%5.2f\n",i,f); //5代表浮点数整体所占是五个位置,2表示小数点后保留两个位置
i=100;
f=98.21; //前面已经定义过了,那么下一次就不用再进行一次定义了
printf(_format:"student number=%-3d score=%5.2f\n,i,f); //默认是右对齐,加个负号是左对齐
printf(_foemat:"%10s\n","hello");
return 0 ;
}
整型进制转换
计算机只能储存二进制,即0和1
一个字节(byte)为八位,一位即二进制的一位(bit),储存0或1
1k = 1024字节
1M=1024kb
1GB=1024MB
十进制 0-9
八进制 0-7
十六进制 0-9 a-f
#include <stdio.h>
int main() {
int i=123;
printf(_format:"%d\n",i); //十进制
printf(_format:"%o\n",i); //八进制
printf(:_format:"%x\n",i); //十六进制
return 0;
}
scanf函数
C语言位提供输入和输出关键字,其输入和输出都输通过标准函数库来实现的。
当scanf函数读取标准输入时,如果还没有输入任何内容,那么scanf函数就会被卡住(专业用语为阻塞)。
#include <stdio.h>
int main() {
int i; //赋不赋值都可以
char c;
scanf(_farmat:"%d",&i); //我们往标准输入里输入的内容都是字符串,scanf根据输入的不同类型储存到变量里 百分号类型和后面那个变量必须是一致的
//scanf把标准输入的内容放到某个变量里,所以变量需要取地址
//这个会卡住,然后我们输入某个值后,才会继续运行
//scanf输入值后必须按回车
//往标准输入里输入了一个值,然而我们不仅输入 了一个值,我们还输入了一个\n
printf(_format:"i=%d\n:,i);
scanf(_format:"%c\n",&c);
flush(_file:stdin)//清空标准输入缓冲区,那么第二个scanf就会卡住了
printf(_format:"c=%c\n",c); //第二个scanf不会卡住是因为第二个scanf会读取第一个scanf遗留的\n,所以并不会卡住
return 0;
}
#include <stdio.h>
int main() {
int i;
float f;
scanf(_format:"%d",&i);
printf(_format:"i=%d\n",i);
scanf(_format:"%f",&f); //没有flush函数也可以卡住,是因为scanf函数读取时会忽略“\n”,空格符等符号。
printf(_format:"%f\n",f);
return 0;
}
scanf一次读多种数据类型
int i,ret;
float f;
char c;
ret=scanf(_format:"%d %c%f",&i,&c,&f); //ret是scanf匹配成功的个数,%c前面有一个空格,%c如果在最开头那就不用了
printf(_format:"i=%d,c=%c,f=%5.2f\n",i,c,f);