C++注释
本身不会被执行, 是给别人看的, 对程序的解释
单行注释 //
多行注释 /* */
变量
给⼀段指定的内存空间起名,⽅便操作这段内存
格式: 数据类型 变量名 = 变量值;
#include <iostream>
using namespace std;
int main(){
// 单行注释
/*
* 多行注释
*/
// 第一种变量声明方式. 声明+初始化
int a = 100; // 声明一个整数型变量a 值为100;
cout<< "a = "<< a << endl;
// 第二种变量声明方式 先声明 在初始化
int b;
b = 200;
cout<< "b = "<< b << endl;
}
常量
作用: ⽤于记录程序中不可更改的数据
C++定义常量两种⽅式
- #define 宏常量: #define 常量名 常量值 通常在⽂件上⽅定义,表⽰⼀个常量
- const修饰的变量 const 数据类型 常量名 = 常量值
通常在变量定义前加关键字const,修饰该变量为常量,不可修改
#include <iostream>
#define PI 3.14
#define week 7
using namespace std;
int main(){
// 变量的值可以修改
// int month = 12;
// month = 100;
// cout<< "一年有 " << month <<" 个月 " <<endl;
// 宏常量 的使用
// PI = 88; 不能修改
cout<< "PI = "<< PI <<endl;
cout<< "一周 week have "<< week << " days" <<endl;
// const 修饰常量
const int month = 12;
// month = 100;
cout<< "一年有 " << month <<" 个月 " <<endl;
}
关键字(保留字)
注意: 在定义变量或者常量时候,不要⽤关键字
作⽤:关键字是C++中预先保留的单词(标识符)
标识符
C++规定给标识符(变量、常量)命名时,有⼀套⾃⼰的规则
- 标识符不能是关键字
- 标识符只能由字⺟、数字、下划线(美元符也行)组成
- 第⼀个字符必须为字⺟或下划线
- 标识符中字⺟区分⼤⼩写
#include <iostream>
using namespace std;
int main(){
# 两个变量
int num = 100;
int NUM = 200;
cout<< num << endl;
cout<< NUM << endl;
}
数据类型
C++规定在创建⼀个变量或者常量时,必须要指定出相应的数据类型,否则⽆法给变量分配内存
- 整型 (integer)
整型变量表⽰的是整数类型的数据
1 字节(Byte) = 8 位(bit)
sizeof关键字
利⽤sizeof关键字可以统计数据类型所占内存⼤⼩
语法: sizeof( 数据类型/ 变量)
#include <iostream>
using namespace std;
int main(){
cout<< " sizeof(short) = " <<sizeof(short)<<endl;
cout<< " sizeof(int) = " <<sizeof(int)<<endl;
cout<< " sizeof(long) = " <<sizeof(long)<<endl;
cout<< " sizeof(long long) = " <<sizeof(long long)<<endl;
}
浮点型(小数/实型)
浮点型有两种
- 单精度float
- 双精度double
两者的区别在于表示有效数字范围不同
#include <iostream>
using namespace std;
int main(){
cout.precision(10); //设置consle输出有效数字的范围
float f1 = 3.141592653f;
double d1 = 3.141592653;
cout<< "f1 ="<< f1 <<endl;
cout<< "d1 ="<< d1 <<endl;
cout<< "sizeof(float) = " <<sizeof(float)<<endl;
cout<< "sizeof(double) = " <<sizeof(double)<<endl;
// 科学计数法
float f2 = 3e2; // 3 x 10 ^2
cout<< "f2 = " <<f2<<endl;
float f3 = -4e3; // -4 x 10 ^3
cout<< "f3 = " <<f3<<endl;
float f4 = 1e-2; // 0.01
cout<< "f4 = " <<f4<<endl;
float f5 = 8e-3; // 0.008
cout<< "f5 = " <<f5<<endl;
}