使用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