📜  使用C ++计算数据类型范围

📅  最后修改于: 2021-06-01 01:55:03             🧑  作者: Mango

用于打印范围数据类型(如int,char,short)的C++程序。

签名数据类型

METHOD
1.) calculate total number of bits by multiplying sizeof with 8 (say n)
2.) Calculate  -2^(n-1) for minimum range
3.) Calculate  (2^(n-1))-1 for maximum range
// CPP program to calculate 
// range of signed data type
#include 
#define SIZE(x) sizeof(x) * 8
using namespace std;
  
// function to calculate range of
//unsigned data type
void printSignedRange(int count)
{
    int min = pow(2, count - 1);
    int max = pow(2, count - 1) - 1;
    printf("%d to %d", min * (-1), max);
}
  
// DRIVER program
int main()
{
    cout << "signed char: ";
    printSignedRange(SIZE(char));
    cout << "\nsigned int: ";
    printSignedRange(SIZE(int));
    cout << "\nsigned short int: ";
    printSignedRange(SIZE(short int));
  
    return 0;
}

输出:

signed char: -128 to 127
signed int: -2147483648 to 2147483647
signed short int: -32768 to 32767

无符号数据类型

METHOD
1.)Find number of bits by multiplying result of sizeof with 8 say n
2.)minimum range is always zero for unsigned data type
3.)for maximum range calculate 2^n-1
// CPP program to calculate range 
// of given unsigned data type
#include 
#define SIZE(x) sizeof(x) * 8
using namespace std;
  
// function to calculate range 
// of given unsigned data type
void UnsignedRange(int count)
{
    // calculate 2^number of bits
    unsigned int max =  pow(2, count) - 1;
  
    cout << "0 to " << max;
}
  
// DRIVER program
int main()
{
    cout << "unsigned char: ";
    UnsignedRange(SIZE(unsigned char));
    cout << "\nunsigned int: ";
    UnsignedRange(SIZE(unsigned int));
    cout << "\nunsigned short int: ";
    UnsignedRange(SIZE(unsigned short));
    return 0;
}

输出:

unsigned char: 0 to 255
unsigned int: 0 to 4294967295
unsigned short int: 0 to 65535
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”