是否有任何代码可以在C/ c++中找到整数的最大值(根据编译器),如integer。java中的MaxValue函数?
当前回答
为什么不写一段这样的代码:
int max_neg = ~(1 << 31);
int all_ones = -1;
int max_pos = all_ones & max_neg;
其他回答
(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;
}
它可能依赖于架构,但至少在我的设置中是有效的。
为什么不写一段这样的代码:
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;