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
-
C ++のPODタイプとは何ですか?
PODはC++の頭字語で、単純な古いデータを意味します。これは、メンバー変数のみを持ち、メソッド、コンストラクタ、デストラクタ、仮想関数などを持たないクラス/構造体です。たとえば、 例 #include<iostream> using namespace std; // POD struct MyStruct { int key; string data; }; int main() { struct MyStruct s; s.key = 1;  
-
C ++の符号付きおよび符号なしキーワードとは何ですか?
C ++のすべての数値タイプには、符号を付けることも付けないこともできます。たとえば、正の整数のみを表すintを宣言できます。特に指定がない限り、すべての整数データ型は符号付きデータ型です。つまり、正または負の値をとることができます。 unsignedキーワードは、符号なしの変数を宣言するために使用できます。 例 #include<iostream> using namespace std; int main() { unsigned int i = -1; int x = i; cout <&l