如何在 C++ 中編寫一個短字面值?


接下來,我們將瞭解如何在 C++ 中編寫短字面值。在 C 或 C++ 中,不同型別的資料有不同的字面值。這些內容如下所示。

序號資料型別和字面值
1int
5
2unsigned int
5U
3Long
5L
4long long
5LL
5float
5.0f
6double
5.0
7char
‘\5’

那麼,我們有 int、long、float、double 等,但沒有 short。所以,我們不能對短型別資料使用任何字面值。但我們可以透過顯式型別轉換解決這個問題。

如果我們使用如下行,那麼它將轉換為 short。

int x;
x = (short) 5; //converted into short type data.

示例

#include <iostream>
using namespace std;
main() {
   int x;
   x = 65700;
   cout << "x is (as integer):" << x << endl;
   x = (short)65700; //will be rounded after 2-bytes
   cout << "x is (as short):" << x << endl;
}

輸出

x is (as integer):65700
x is (as short):164

更新於:2019 年 7 月 30 日

722 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.