C++学习记录9:short,long,long long大小,以及climits

编程中常常会有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_MAXint的最大值
SHRT_MAXshort的最大值
LONG_MAXlong的最大值
INT_MINint的最小值
CHAR_BITchar的位数

long long由于笔者用的VC++6.0,系统不支持,所以删除了那一行,下面是加上后供参考的

LLONG_MAXlong 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值