C++基础入门---2.数据类型【P8~P15】
2. 数据类型
C++规定在创建一个变量或者常量时,必须要指定相应的数据类型,否则无法给变量分配内存。
2.1 数据类型,整型
# include <iostream>
using namespace std;
int main()
{
//整型
//短整型 short int(-32768~32767)
short int num1 = 10;
//整型 Int
int num2 = 10;
//长整型
long num3 = 10;
//长长整型 long long int
long long int num4 = 10;
cout << "num1= " << num1 << endl;
cout << "num2= " << num2 << endl;
cout << "num3= " << num3 << endl;
cout << "num4= " << num4 << endl;
system("pause");
return 0;
}
2.2 数据类型,sizeof关键字
# include <iostream>
using namespace std;
int main()
{
short num0 = 2;
int num1 = 2;
long num2 = 2;
long long num3 = 2;
cout << "num1 的内存大小为: " << sizeof(int) << endl;
cout << "num1 的内存大小为: " << sizeof(num1) << endl;
cout << "num2 的内存大小为: " << sizeof(num3) << endl;
system("pause");
return 0;
}
2.3 数据类型,实型(浮点型)
# include <iostream>
using namespace std;
int main()
{
float A = 3.14f;
double B = 3.14;
cout << " A = " << A << endl;
cout << " B = " << B << endl;
cout << " float 占用的内存大小为: " << sizeof(float) << endl;
cout << " double 占用的内存大小为: " << sizeof(double) << endl;
//科学计数法
float C = 3e2; //3*10^2
cout << " C = " << C << endl;
float D = 3e-2; //3*0.1^2
cout << " D = " << D << endl;
system("pause");
return 0;
}
目前c++中默认会给显示出6位有效数字。
2.4 数据类型,字符型
# include<iostream>
using namespace std;
int main()
{
//1.创建字符型变量
char ch = 'a';
cout << " ch = " << ch << endl;
//2.字符型变量所占内存大小
cout << " char 所占内存大小为: " << sizeof(char) << endl;
//3.字符型变量对应ascll编码
cout << " a 对应的ASCLL码是: " << int(ch) << endl;
system("pause");
return 0;
}
2.5 数据类型,转义字符
# include<iostream>
using namespace std;
int main()
{
//1.换行符\n
cout << " Hello World !\n ";
//2.反斜杠 \\
cout << " \\ " << endl;
//3.水平制表符 \t,制表符占8个位置
cout << " AAA\tHello World !" << endl;
cout << " AA\tHello World !" << endl;
cout << " AAAAAA\tHello World !" << endl;
system("pause");
return 0;
}
2.6 数据类型,字符串类型
# include<iostream>
# include<string> //用c++风格的字符串要包含这个头文件
using namespace std;
int main()
{
//C风格字符串
char str[] = "Hello World !";
cout << str << endl;
//C++风格字符串
string A = "Hello World !";
cout << A << endl;
system("pause");
return 0;
}
2.7 数据类型,布尔类型
# include<iostream>
using namespace std;
int main()
{
bool flag = true;
cout << flag << endl;
bool flag2 = false;
cout << flag2 << endl;
cout << " bool 类型所占内存是: " << sizeof(bool) << endl;
system("pause");
return 0;
}
2.8 数据类型,数据的输入
# include<iostream>
using namespace std;
int main()
{
//整型
int a = 0;
cout << " 请给整型变量a赋值: " << endl;
cin >> a;
cout << "整型变量 a = " << a << endl;
//浮点型
float f = 3.14f;
cout << " 请给浮点型变量f赋值: " << endl;
cin >> f;
cout << "浮点型变量 f = " << f << endl;
//字符型
//字符串型
//布尔型
system("pause");
return 0;
}