是否有任何代码可以在C/ c++中找到整数的最大值(根据编译器),如integer。java中的MaxValue函数?
当前回答
#include <climits>
#include <iostream>
using namespace std;
int main() {
cout << INT_MAX << endl;
}
其他回答
好吧,我没有代表评论之前的答案(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;
与使用这个或那个头文件不同,这里我们使用来自编译器的真实类型。
为什么不写一段这样的代码:
int max_neg = ~(1 << 31);
int all_ones = -1;
int max_pos = all_ones & max_neg;
#include <climits>
#include <iostream>
using namespace std;
int main() {
cout << INT_MAX << endl;
}
在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;
(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))可以。