使用 C++ 計算資料型別的範圍


在 C++ 中,我們有不同的資料型別,如 int、char、double 等等。在本節中,我們將看到如何以程式設計方式獲取其大小。

我們可以按位元組獲取資料型別的大小,因此我們可以簡單地將它們乘以 8 以獲取以位為單位的值。現在我們知道,如果位數為 n,則有符號數的最小範圍將為 – 2^(n-1),最大範圍將為 2^(n-1) – 1。對於無符號數,由於沒有負數,因此它將為 2^n – 1。

示例程式碼

#include <iostream>
#include <cmath>
#define SIZE(x) sizeof(x) * 8 //Get the size in bits
using namespace std;
void getRange(string type, int n) {
   if(type.compare("SIGNED") == 0) { //for signed numbers calculate lower and upper limit
      int min = pow(2, n - 1);
      int max = pow(2, n - 1) - 1;
      cout << "Range from " << (-1) * min << " to " << max <<endl;
   }else{ //for signed numbers calculate limit from 0
      int range = pow(2, n )-1;
      cout << "Range from 0 to " << range << endl;
   }
}
int main() {
   cout << "For Signed int: ";
   getRange("SIGNED", SIZE(int));
   cout << "For Signed float: ";
   getRange("SIGNED", SIZE(float));
   cout << "For Unsigned int: ";
   getRange("UNSIGNED", SIZE(unsigned int));
   cout << "For Unsigned short: ";
   getRange("UNSIGNED", SIZE(unsigned short int));
   cout << "For Signed char: ";
   getRange("SIGNED", SIZE(char));
}

輸出

For Signed int: Range from -2147483648 to 2147483647
For Signed float: Range from -2147483648 to 2147483647
For Unsigned int: Range from 0 to -2147483648
For Unsigned short: Range from 0 to 65535
For Signed char: Range from -128 to 127

更新於: 30-Jul-2019

4K+ 瀏覽量

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.