是否有任何代码可以在C/ c++中找到整数的最大值(根据编译器),如integer。java中的MaxValue函数?
在c++中:
#include <limits>
然后使用
int imin = std::numeric_limits<int>::min(); // minimum value
int imax = std::numeric_limits<int>::max();
numeric_limits是一个模板类型,可以用其他类型实例化:
float fmin = std::numeric_limits<float>::min(); // minimum positive value
float fmax = std::numeric_limits<float>::max();
在C:
#include <limits.h>
然后使用
int imin = INT_MIN; // minimum value
int imax = INT_MAX;
or
#include <float.h>
float fmin = FLT_MIN; // minimum positive value
double dmin = DBL_MIN; // minimum positive value
float fmax = FLT_MAX;
double dmax = DBL_MAX;
#include <climits>
#include <iostream>
using namespace std;
int main() {
cout << INT_MAX << endl;
}
为什么不写一段这样的代码:
int max_neg = ~(1 << 31);
int all_ones = -1;
int max_pos = all_ones & max_neg;
我知道这是一个老问题,但也许有人可以使用这个解决方案:
int size = 0; // Fill all bits with zero (0)
size = ~size; // Negate all bits, thus all bits are set to one (1)
到目前为止,我们的结果是-1,直到size是一个带符号的int型。
size = (unsigned int)size >> 1; // Shift the bits of size one position to the right.
正如标准规则所说,如果变量是有符号且为负,则移位的位为1,如果变量是无符号或有符号且为正,则移位的位为0。
因为size是带符号且为负的,我们将符号位移位为1,这没有多大帮助,所以我们强制转换为unsigned int,将符号位改为0,同时让所有其他位保持1。
cout << size << endl; // Prints out size which is now set to maximum positive value.
我们也可以使用掩码和xor但我们必须知道变量的确切位大小。通过前面移位位,我们不需要知道int在机器或编译器上有多少位,也不需要包含额外的库。
下面是一个宏,用于获取有符号整数的最大值,它与所使用的有符号整数类型的大小无关,并且gcc -Woverflow不会报错
#define SIGNED_MAX(x) (~(-1 << (sizeof(x) * 8 - 1)))
int a = SIGNED_MAX(a);
long b = SIGNED_MAX(b);
char c = SIGNED_MAX(c); /* if char is signed for this target */
short d = SIGNED_MAX(d);
long long e = SIGNED_MAX(e);
好吧,我没有代表评论之前的答案(Philippe De Muyter),也没有提高它的分数,因此有一个新的例子,使用他对SIGNED_MAX的定义,简单地扩展为unsigned类型:
// We can use it to define limits based on actual compiler built-in types also:
#define INT_MAX SIGNED_MAX(int)
// based on the above, we can extend it for unsigned types also:
#define UNSIGNED_MAX(x) ( (SIGNED_MAX(x)<<1) | 1 ) // We reuse SIGNED_MAX
#define UINT_MAX UNSIGNED_MAX(unsigned int) // on ARM: 4294967295
// then we can have:
unsigned int width = UINT_MAX;
与使用这个或那个头文件不同,这里我们使用来自编译器的真实类型。
(1 < <呢(8 * sizeof (int) 2)) - 1 + (1 < < (8 * sizeof (int) 2))。 这就等于2^(8*sizeof(int)-2) - 1 + 2^(8*sizeof(int)-2)
如果sizeof(int) = 4 => 2^(8*4-2) - 1 + 2^(8*4-2) = 2^30 - 1 + 20^30 =(2^32)/2 - 1[最大signed int of 4字节]。
你不能使用2*(1 << (8*sizeof(int)-2)) - 1,因为它会溢出,但是(1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2))可以。
#include <iostrema>
int main(){
int32_t maxSigned = -1U >> 1;
cout << maxSigned << '\n';
return 0;
}
它可能依赖于架构,但至少在我的设置中是有效的。
推荐文章
- Std::auto_ptr改为Std::unique_ptr
- int的最大值
- c++中有最大数组长度限制吗?
- 什么是“参数依赖查找”(又名ADL,或“Koenig查找”)?
- 公共朋友交换成员函数
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- 如何在Go中使用c++
- 自定义c++分配器的引人注目的例子?
- RAII和c++中的智能指针
- 如何构建和使用谷歌TensorFlow c++ api
- C“int”的大小是2字节还是4字节?
- 多维数组如何在内存中格式化?
- printf()和puts()在C语言中的区别是什么?
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?