C++学习(二)

来源:互联网 发布:网络舆情分析技术 编辑:程序博客网 时间:2024/05/19 11:17

C++的数据类型。


一、
表示整数,字符和布尔值的算术类型合称为整型(integral type)。
short,int,long类型都是表示整型值,区别是存储空间大小不同。
int一般都是4字节(32位)或者8字节(64位),能表示的范围:-2147483648~2147483647(- 2^31 ~ 2^31 - 1)
short 一般是2字节(16位)相当于word或者int16,表示的数值范围: - 32768 ~ 32767
long 4字节(32位),表示数值范围-2147483648~2147483647


我们来写个程序看看这几个类型的区别


1、
#include "stdafx.h"
#include "iostream"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
short int a = 32767;
cout << a << endl;
return 0;
}


将a = 32767改为a = 32768,调试输出就变成了- 32768。表示这个设置超出了short int 这个类型的范围。


2、
#include "stdafx.h"
#include "iostream"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
long int a = 2147483647;
cout << a << endl;
return 0;
}


a = 2147483647改为a = 2147483648,输出变为-2147483648了。超了范围。
改为a =-2147483649,输出为2147483647。long int的数值范围只能在:-2147483648~2147483647



直接定义int a = 2147483647;状况跟long int 同。


二、bool类型,大小是一个字节。
先看下面的程序
#include "stdafx.h"
#include "iostream"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
bool a = 6;
cout << a << endl;
return 0;
}


调试输出值是1,a = 345235也是输出1,改为bool a = 0;输出为0
bool类型的值只有0和1,0代表FALSE ,1代表TRUE。返回值为>0的整数为TRUE,0为FALSE。
一般用来进行一些判断时用。

三、char字符型。其值只能为一个字符。


#include "stdafx.h"
#include "iostream"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
char a = 'K';
cout << a << endl;
return 0;
}
输出K
改为char a = 'KTP';输出为:P。char字符型接收的是右边第一个字符。



三、wchar_t,宽字符,占两个字节16位。
#include "stdafx.h"
#include "iostream"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
wchar_t a = L'嗯';
wcout.imbue(locale("chs"));//设置wcout的本地化属性
wcout << a << endl;//输出宽字符
return 0;
}
注意到,输出不是cout了,而是用字符的输出wcout。




四、float单精度浮点型,6位有效数值。
#include "stdafx.h"
#include "iostream"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
float a =2.123452;
cout << a << endl;
return 0;
}
输出为:2.12345。


改为a =452.123452;
输出:a =452.123


不过,改为 a =34.123452,输出是 34.1235,为什么不是34.1234?不知道是不是编译器的问题。




五、double双精度浮点型,10位有效数值。略......
六,long double扩展精度浮点型,10位有效数值。略......