编程中常常会有short ,long , long long等前缀,希望下面的代码会对你有所帮助
short至少16位
int至少和short一样长
long至少32位,且至少和int一样长
long long至少64位,且至少与long一样长
#include<iostream> /*在本文件中所有大写后_MAX或者_MIN是
在climits文件夹里进行标志化定义后的数据数值 */
#include<climits> //limits.hshi适用于老系统
int main()
{
using namespace std;
int n_int = INT_MAX; //对n_int进行初始化来使int值最大化
short int n_short = SHRT_MAX; //在climits文件夹里进行标志化定义
long int n_long = LONG_MAX;//其实这里应该还有一个long long的形势,有些系统不支持
//sizeof函数作用是显示某个数据内存的大小
cout<<"int is "<<sizeof(int)<<" bytes."<<endl;
cout<<"short is "<<sizeof n_short<<" bytes."<<endl;
cout<<"long is "<<sizeof n_long<<" bytes."<<endl;
cout<<endl;
cout<<"Maximum values:"<<endl;
cout<<"int: "<<n_int<<endl;
cout<<"short: "<<n_short<<endl;
cout<<"long: "<<n_long<<endl;
cout<<"Minimum int value = "<<INT_MIN<<endl;//在climits文件夹里进行标志化定义
cout<<"Bits per byte = "<<CHAR_BIT<<endl;
return 0;
}
运行结果
int is 4 bytes.
short is 2 bytes.
long is 4 bytes.
Maximum values:
int: 2147483647
short: 32767
long: 2147483647
Minimum int value = -2147483648
Bits per byte = 8
Press any key to continue
本代码源于笔者暑假学习的C++ prime plus里的内容,climits.h的原理是定义最大能表达的数,如:
#define INT_MAX 32767
头文件climits定义了符号常量来表示类型的限制。如前所述,INT_MAX表示int能够储存的最大值,对于windows7系统,为2 147 483 647
上述代码中对应的climits部分符号常量在下面的表格中
INT_MAX | int的最大值 |
SHRT_MAX | short的最大值 |
LONG_MAX | long的最大值 |
INT_MIN | int的最小值 |
CHAR_BIT | char的位数 |
long long由于笔者用的VC++6.0,系统不支持,所以删除了那一行,下面是加上后供参考的
LLONG_MAX | long long的最大值 |
#include<iostream>
#include<climits>
int main()
{
using namespace std;
int n_int = INT_MAX;
short int n_short = SHRT_MAX;
long int n_long = LONG_MAX;
long long n_llong = LLONG_MAX;
cout<<"int is "<<sizeof(int)<<" bytes."<<endl;
cout<<"short is "<<sizeof n_short<<" bytes."<<endl;
cout<<"long is "<<sizeof n_long<<" bytes."<<endl;
cout<<"long long is "<<sizeof n_llong<<" bytes."<<endl;
cout<<endl;
cout<<"Maximum values:"<<endl;
cout<<"int: "<<n_int<<endl;
cout<<"short: "<<n_short<<endl;
cout<<"long: "<<n_long<<endl;
cout<<"long long: "<<n_llong<<endl;
cout<<"Minimum int value = "<<INT_MIN<<endl;
cout<<"Bits per byte = "<<CHAR_BIT<<endl;
return 0;
}