数值型别的极值

1.引言

       在阅读别人的代码的时候,经常遇到最大的int值赋值为0x7FFFFFFF,最小的int值赋值为0x80000000

       最大值易于理解,但是最小值为什么是0x80000000

       首先注意,当给变量按16进制赋值的时候,是按补码形式赋值的。但是有一个特例就是0x80000000,这个是最小的负数,因为负数比正数表示的范围多1,所以0x80000000是没有原码的。

       看下面一段测试程序:

int main ()
{
	int a=0x7FFFFFFF;
	int b=0x80000000;
	int c=0x80000007;
	int d=0xFFFFFFF9;//0xffffffff(-1)-0x6
	cout << "最大的正数:" << a << endl;
	cout << "最小的负数:" << b << endl;
	cout << "-7原码:" << c << endl;
	cout << "-7补码:" << d << endl;
	return 0;
}

2.<limits>

       一般来说,数值型别的极值是一个与平台相关的特性。C++标准程序库通过template numeric_limits提供这些机制,取代传统的C语言所彩专用的预处理器常数。但是C语言版本仍然可用,其中正数常数定义于<limits.h>,浮点型常数定义于<float.h>。而在C++中所有型别机制都定义于<limits>

       下面给出一个测试程序:

#include <limits>
#include <iostream>
using namespace std;

int main ()
{
	cout<<"输出各类最大值"<<endl;
	
	cout<< "int,max:" << numeric_limits<int>::max() << endl;
	cout<< "unsigned int,max:" <<  numeric_limits<unsigned int>::max() <<endl; 
	cout<< "char,max:" << (int)numeric_limits<char>::max() << endl;
	cout<< "unsigned char,max:" << (unsigned int)numeric_limits<unsigned char>::max() << endl;
	cout<< "long,max:" << numeric_limits<long int>::max() <<endl; 
	cout<< "float,max:" << numeric_limits<float>::max() <<endl<<endl; 
		
	cout<<"输出各类最小值"<<endl;
			
	cout<< "int,min:" << numeric_limits<int>::min() << endl;
	cout<< "unsigned int,min:" << numeric_limits<unsigned int>::min() <<endl;
	cout<< "char,min:" << (int)numeric_limits<char>::min() << endl;
	cout<< "unsigned char,min:" << (unsigned int)numeric_limits<unsigned char>::min() << endl;
	cout<< "long,min:" << numeric_limits<long int>::min() <<endl;
	cout<< "float,min:" << numeric_limits<float>::min() <<endl<<endl; 
		
	cout<<"测试最大的int值上溢出之后的值"<<endl;
	int a=numeric_limits<int>::max();
	cout <<a<<endl;
	a++;
	cout <<a<<endl;
	cout<<"结果为最小的int值(负数)"<<endl<<endl;
		
	cout<<"测试最小的int值下溢出之后的值"<<endl;	
	a=numeric_limits<int>::min();
	cout <<a<<endl;
	a--;
	cout <<a<<endl;
	cout<<"结果为最大的int值(负数)"<<endl<<endl;
	return 0;
}



 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值