基础(一):
基础(一):
变量
#include <iostream>
using namespace std;int main()
{int a = 10;cout << "a=" << a << endl;system("pause");return 0;
}
常量
- #define 宏常量 :#define 常量名 常量值
- 通常在文件上方定义,表示一个常量
- const 修饰的变量:const 数据类型 常量名 = 常量值
- 通常在变量定义前加关键字const,修饰该变量为常量,不可修改
#include <iostream>
using namespace std;
// 宏常量
#define day 7int main()
{cout << "一周有" << day << "天" << endl;// const修饰变量const int month = 12;cout << "一年有" << month << "月" << endl;system("pause");return 0;
}
标识符命名规则
- 标识符不能是关键字;
- 标识符只能由字母、数字、下划线组成;
- 第一个字符必须为字母或下划线;
- 标识符中字母区分大小写。
数据类型
整型
作用:整型变量表示的是整数类型的数据;C++中能够表示整型的类型由以下几种方式,区别在于所占内存空间不同。
数据类型 | 占用空间 | 取值范围 |
---|---|---|
short(短整型) | 2字节 | (-215~215-1) |
int(整型) | 4字节 | (-231~231-1) |
long(长整型) | window:4字节,Linux:4字节(32位),8字节(64位) | (-231~231-1) |
long long(长长整型) | 8字节 | (-263~263-1) |
sizeof关键字
作用:利用 sizeof 关键字可以统计数据类型所占内存大小。
语法:sizeof(数据类型或变量)
#include <iostream>
using namespace std;
// short(2) int(4) long(4) long long(4)
int main()
{short num1 = 10;cout << "short占用内存空间:" << sizeof(short) << endl;int num2 = 10;cout << "int占用内存空间:" << sizeof(int) << endl;long num3 = 10;cout << "long占用内存空间:" << sizeof(long) << endl;long long num4 = 10;cout << "long long占用内存空间:" << sizeof(long long) << endl;system("pause");return 0;
}
实型(浮点型)
数据类型 | 占用空间 | 有效数字范围 |
---|---|---|
float | 4字节 | 7位有效数字 |
double | 8字节 | 15~16位有效数字 |
#include <iostream>
using namespace std;int main()
{float f1 = 3.14f;double d1 = 3.14;cout << f1 << endl;cout << d1 << endl;cout << "f1所占内存空间大小:" << sizeof(float) << endl; //4cout << "d1所占内存空间大小:" << sizeof(double) << endl;//8float f2 = 3e2;cout << "f2 = " << f2 << endl;double d2 = 3e-2;cout << "d2 = " << d2 << endl;system("pause");return 0;
}
字符型
作用:字符型变量用于显示单个字符
语法:char ch = ‘a’ ; // 占用一个字节,字符型变量并不是把字符本身放在内存中,而是将对应的ASCII编码放入到存储单元 a–97 A --65
# include <iostream>
using namespace std;int main()
{char ch = 'A';cout << ch << endl;cout << (int)ch << endl;cout << "char所占内存空间的大小:" << sizeof(char) << endl; // 1system("pause");return 0;
}