是否有任何代码可以在C/ c++中找到整数的最大值(根据编译器),如integer。java中的MaxValue函数?
当前回答
#include <iostrema>
int main(){
int32_t maxSigned = -1U >> 1;
cout << maxSigned << '\n';
return 0;
}
它可能依赖于架构,但至少在我的设置中是有效的。
其他回答
在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;
}
#include <iostrema>
int main(){
int32_t maxSigned = -1U >> 1;
cout << maxSigned << '\n';
return 0;
}
它可能依赖于架构,但至少在我的设置中是有效的。
好吧,我没有代表评论之前的答案(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;