C++基礎資料型別 (Elementary Data Type)轉換

來源:互聯網
上載者:User

標籤:name   算術   寬度   int   類型   位元組   整型   符號   否則   

切勿混合使用無符號類型和有符號類型,否則產生極大的錯誤。

C++不會直接把兩種不同類型的值相加,而是先根據類型轉換的法則轉換成同一類型後再相加。

類型轉換算術轉換

1, char,unsigned char,signed char,short,unsigned short

     char,unsigned char,signed char,short,unsigned short 提升成int 類型或 unsigned int 類型。

     wchar_t  char16_t  char32_t 提升成int unsigned int  long unsigned long long long unsigned long中最小的一種類型。

2, int  ,unsigned int , long , unsigned long, long long ,unsigned long long 

    不看類型!只看所佔位元組寬度!

    類型所佔位元組寬窄不同:窄位元組轉成寬位元組

    類型所佔位元組寬窄相同:有符號轉成無符號

    舉例:

    long 和 unsigned int,如果long是4位元組則 long 轉換成 unsigned int ;如果long是8位元組,則unsigned int 轉換成  long 。

    unsigned int 和 int  轉成int 轉換成 unsigned int 。

3,整型與浮點型:整型轉成浮點型。

4,float 轉換成 double 。

  有符號數轉換成無符號數的注意點!

1

    unsigned int u = 10;    int b = -42;    std::cout << b + b << std::endl;//-48    std::cout << u + b << std::endl;//4294967264

 

2

不帶正負號的整數,必須大數 - 小數 。

 

3

for(unsigned int i = 10; i >= 0 ; --i)  ;//死迴圈

 

#include<iostream>using namespace std;int main() {    unsigned int u1 = 10;    unsigned int u2 = 20;    cout << u2 - u1 << endl;//10    cout << u1 - u2 << endl;//4294967286    unsigned int u3 = 1;    int i = -2;    cout << u3 + i << endl;//4294967295    system("pause");}

 

C++基礎資料型別 (Elementary Data Type)轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.