C/C++及其应用程序中的INT_MAX和INT_MIN

大多数情况下,在竞争性编程中,需要分配变量,即数据类型可以容纳的最大值或最小值,但记住如此大而精确的数字是一项困难的工作。因此,C++具有某些宏来表示这些数字,因此这些代码可以直接分配给变量而不必键入整个数字。

null

根据编译器和C++标准,您可能需要包含头文件。 在你的C或C++源代码中分别。因此,建议在使用INT_MAX和INT_MIN宏时包含此头文件。要进一步阅读此头文件, 请参阅本文 .

INT_MAX是一个宏,指定整数变量不能存储超过此限制的任何值。 INT_MIN指定整数变量不能存储低于此限制的任何值。

Values of INT_MAX and INT_MIN may varyfrom compiler to compiler. Following aretypical values in a compiler where integersare stored using 32 bits.Value of INT_MAX is +2147483647.Value of INT_MIN is -2147483648.

CPP

// C++ program to print values of INT_MAX
// and INT_MIN
#include <bits/stdc++.h>
using namespace std;
int main()
{
cout << INT_MAX << endl;
cout << INT_MIN;
return 0;
}


C

// C program to print values of INT_MAX
// and INT_MIN
// we have to include limits.h for results in C
#include <limits.h>
#include <stdio.h>
int main()
{
printf ( "%d" , INT_MAX);
printf ( "%d" , INT_MIN);
}


输出

2147483647-2147483648

INT_MAX和INT_MIN的应用:

1.检查整数溢出:

CPP

// C++ code to check for Integer overflow while
// adding 2 numbers
#include <bits/stdc++.h>
// Function to check integer overflow
int check_overflow( int num1, int num2)
{
// Checking if addition will cause overflow
if (num1 > INT_MAX - num2)
return -1;
// No overflow occured
else
return num1 + num2;
}
// Driver code
int main()
{
// The sum of these numbers will equal INT_MAX
// If any of them is incremented by 1, overflow
// will occur
int num1 = 2147483627;
int num2 = 20;
// Result is -1 if overflow occurred
// Stores the sum, otherwise
int result = check_overflow(num1, num2);
// Overflow occurred
if (result == -1)
std::cout << "Integer overflow occurred" ;
// No overflow
else
std::cout << result;
}


输出

2147483647

类似地,我们可以在使用INT_MIN减去2个数字时检查溢出。

2.计算大元素数组中的最小值 我们通常将一个高值赋给MIN,以计算数组中的最小值。但是,如果一个数组有大的元素,我们必须为该数组指定尽可能高的值。

下面是C++实现:

CPP

// C++ code to compute MIN element
#include <bits/stdc++.h>
// Function to compute minimum element in array
int compute_min( int arr[], int n)
{
// Assigning highest value
int MIN = INT_MAX;
// Traversing and updating MIN
for ( int i = 0; i < n; i++)
MIN = std::min(MIN, arr[i]);
// Printing MIN element
std::cout << MIN;
}
// Driver code
int main()
{
// array with MIN to compute
int arr[] = { 2019403813, 2147389580, 2145837140,
2108938594, 2112076334 };
// size of array
int n = sizeof (arr) / sizeof (arr[0]);
// Function call to compute MIN
compute_min(arr, n);
}


输出

2019403813

类似地,可以使用INT_MIN在一个大数字数组中找到MAX。

本文由 罗希特·塔普里亚尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享