使用 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+ 浏览量

开启您的 职业生涯

完成课程后获得认证

开始
广告