C++ Primer基本內置類型

基本內置類型

1.void類型

void doA()
{
}

空類型,這個類型的函數沒有返回值。

2.int型

int doB()
{
    int a=4;
    return a;
}
整型,返回值爲整數,創建的變量也爲整數。

3.float型

float doC()
{
      float c=0.1;
      return c;
}
浮點型,返回值爲浮點數,創建的變量也爲浮點數。

4.char型

char  doD()
{
      char d='a';
      return d;
}
字符型,返回值爲一個字符,創建的變量也爲字符。

5.bool型

char doE()
{
       bool FF=false;
       return FF;
}
布爾型,返回真或假,是一個判斷類型。


字符類型的空間

以上5種就是基礎的數據類型,出此之外還有幾種擴展類型:
類型 含義 機器字 最小存儲空間
bool 布爾型
-
char 字符型
8位 標準字符型
wchar_t 寬字符型
16位 用來存儲中文等字符
short 短整型 半個機器字 16位
int 整型 1個機器字 16位 標準字符型
long 長整型 1或2個機器字 32位
float 單精度浮點型
6位有效數字
double 雙精度浮點型
10位有效數字 標準浮點型,最快的浮點型
long double

10位有效數字

函數sizeof(),計算數據空間的字節數。

#include<iostream>

int main()
{
	std::cout << "bool:\t\t" << sizeof(bool) << std::endl;
	std::cout << "char:\t\t" << sizeof(char) << std::endl;
	std::cout << "wchar_t:\t" << sizeof(wchar_t) << std::endl;
	std::cout << "short:\t\t" << sizeof(short) << std::endl;
	std::cout << "int:\t\t" << sizeof(int) << std::endl;
	std::cout << "long:\t\t" << sizeof(long) << std::endl;
	std::cout << "float:\t\t" << sizeof(float) << std::endl;
	std::cout << "double:\t\t" << sizeof(double) << std::endl;
	std::cout << "long double:\t" << sizeof(long double) << std::endl;
	system("pause");
	return 0;
}

結果:
bool:                1
char:                1
wchar_t:          2
short:               2
int:                    4
long:                 4
float:                 4
double:             8
long double:    8

溢出

unsigned 表示無符號數,也就是都爲整數。如unsigned int表示正整數
signed表示有符號數,可省略。如 (signed) int整數
類型 空間 2進制最大數 10最大數 2最小數 10最小數
unsigned char 8位 2^8-1 255 0 0
char 8位 2^7-1 127 -2^7 -128
unsigned short 16位 2^16-1 65535 0 0
short 16位 2^15-1 32767 -2^15 -32768
unsigned int 32位 2^32-1 4294967295 0 0
int 32位 2^31-1 2147483647 -2^31 -2147483648

當我們向一個變量賦值時,若數字溢出,則會從變量的最小值從頭開始賦值。
#include<iostream>
using namespace std;
int main()
{
	unsigned char a = 255;
	unsigned char b = 256;
	printf("%d  %d\n", a,b);
	system("pause");
	return 0;
}
結果爲和255  0。

例題:

習題2.3
如果在某機器上short類型佔16位,那麼可以賦給short類型的最大數是什麼?Unsigned short類型的最大數又是什麼?
#include<iostream>
using namespace std;
int main()
{
	unsigned short a1 = 65535, a2 = a1 + 1;
	short b1 = 32767,b2=b1+1;
	cout << a1 << "   " << a2<<endl;
	cout << b1 << "   " << b2<<endl;
	system("pause");
	return 0;
}

結果:
65535   0
32767   -32768

習題2.4
當給16位的unsigned short對象賦值100000時,賦的值是什麼?
#include<iostream>
using namespace std;
int main()
{
	unsigned short a = 100000;
	cout << a<<endl;
	system("pause");
	return 0;
}

結果:34464,即爲100000%65535(unsigned short的最大數)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章