一、在c++中的數據類型轉換一般有以下幾種情況:
1、將一種算術類型的值賦給另一種算術類型的變量時,c++將對值進行轉換
2、表達式中包含不同的類型時,c++將對值進行轉換
3、將參數傳遞給函數時,c++將對值進行轉換
二、在進行數據類型轉換的時候要注意幾點:
1、將小的數據類型轉化為大的數據類型,不會出現問題,一般只是轉化后所占用的字節更多了,但是要將大的數據類型轉化為小的數據類型的話,就會造成數據的丟失。
2、將較大的浮點數轉化為較小的浮點數,如double轉化為float ,這會造成精度(有效數位)降低,值可能超出目標類型的取值范圍,在這種情況下,結果將是不確定的。
3、將浮點類型轉換為整型,這會造成小數部分丟失,原來的值可能超出目標類型的取值范圍,在這種情況下,結果將是不確定的。
4、當運算涉及到兩種數據類型時,一般是較小的類型將被轉換為較大的類型。
三、強制類型轉換:
1、形式:
a、(typeName) value (C語言的寫法)
b、value (typeName) (c++的寫法)
c、static_cast<> 可以將值從一種數值類型轉換為另外一種數據類型,格式為: static_cast<typeName> (value)
例如:
1 #include <iostream> 2 int main() 3 { 4 using namespace std; 5 int auks ,bats , coots; 6 auks=19.99+11.99; 7 8 bats=(int)19.99+(int)11.99; 9 coots=int(19.99)+int(11.99); 10 cout<<"auks="<< auks <<",bats = "<< bats; 11 cout<<",coots = "<<coots<<endl; 12 13 char ch ='Z'; 14 cout<<"The code for " << ch << "is"; 15 cout<<int(ch)<<endl; 16 cout<<"yes,the code is "; 17 cout<<static_cast<int>(ch)<<endl; 18 return 0; 19 }
結果如下:
auks=31,bats = 30,coots = 30 The code for Zis90 yes,the code is 90
四、總結:
整型數據類型大小排序: bool , char , signed char, unsigned char, short , unsigned short , int , unsigned int ,long , unsigned long , long long , unsigned long long
浮點數排序大小:float , double , long double