【C/C++】一篇小文速通 数据类型
1. int、short、long
#include <iostream>
using namespace std;
int main()
{cout << "int 占用内存空间为:" << sizeof(int) << endl;cout << "short 占用内存空间为:" << sizeof(short) << endl;cout << "long 占用内存空间为:" << sizeof(long) << endl;cout << "long long 占用内存空间为:" << sizeof(long long) << endl;cout << "float 占用内存空间为:" << sizeof(float) << endl;cout << "double 占用内存空间为:" << sizeof(double) << endl;}
在Windows×64下,
事实上,short<int<=long<=long long
sizeof可以直接测数据类型所占字节,也可直接测给的数据
2. float和double
默认输入的小数是double型,如果结尾加上f,则转成float型
注意区分有效数字和小数点后几位
3.14159是6位有效数字,C++中默认输出小数显示出6位有效数字
#include <iostream>
using namespace std;int main()
{float f1 = 3.1415926f;cout << "f1=" << f1 << endl;double d1 = 3.1415926f;cout << "d1=" << d1 << endl;
}
在Windows×64下,
3. 字符型
易错点:
创建字符型变量要用单引号
创建字符型变量时单引号内只能有一个字符
想知道 字符型变量对应ASCII编码,前加括号强转为整数类型
#include <iostream>
using namespace std;int main()
{char ch = 'a';cout << ch << endl;cout << "char字符型变量 占用内存空间为:" << sizeof(char) << endl; cout << (int)ch << endl;
}
先记住这两个~
4.转义字符
用于表示不能显示出来的ASCII字符
现阶段常用的转义字符:\n (换行符) \\(反斜杠) \t(水平制表符)
#include <iostream>
using namespace std;
int main()
{cout << "hello\n" << endl;cout << "aaa\thello" << endl;cout << "hello\\" << endl;
}
5. 字符串型
5.1 C风格字符串
char str[]="hello xiaobai";
注意要加上方括号[]
5.2 C++风格字符串
string str2 = "hello xiaobai";
注意要包含头文件,在开头加上 #include <string>
想继续了解可点击以下链接
string类https://blog.csdn.net/2301_76153977/article/details/150420011?spm=1001.2014.3001.5502
6. 布尔类型bool
只有两个值:true和false
#include <iostream>
using namespace std;
int main()
{bool flag = true;cout << flag << endl;flag = false;cout << flag << endl;cout << "bool 占用内存空间为:" << sizeof(bool) << endl;}
7. 数据的输入
套路一样:都是先初始化,再cin你主动输入一个,最后cout输出
#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;//字符型char ch = 'a';cout << "请给字符型变量ch赋值:" << endl;cin >> ch;cout << "字符型变量ch=" << ch << endl;//字符串型string str = "xiaobai";cout << "请给字符串型变量str赋值:" << endl;cin >> str;cout << "字符串型变量str=" << str << endl;//bool型bool flag = false;cout << "请给bool型变量flag赋值:" << endl;cin >> flag;cout << "bool型变量flag=" << flag << endl;
}
想了解更多,推荐此书https://blog.csdn.net/2301_76153977/article/details/151447774