midpoint() in C++20 with Examples
Last Updated :
27 Aug, 2021
The function midpoint() computes the midpoint of the integers, floating-points, or pointers a and b.
Header File:
<numeric>
Parameters: This function accepts two data types like integers, floating points, pointer values.
Return:
It returns the midpoints of the given data types.
Algorithm this function implements:
- Half the sum of a and b without any overflow. Same as, (a + b)/2.
- If a and b are integer types and the sum is odd, the result is rounded towards a.
- If a and b are floating-point types, at most one inexact operation occurs (rounded towards zero).
- If a and b are pointing to x[i] and x[j] respectively of the same array object x (for the purpose of pointer arithmetic), the result will be a pointer to x[i + (j – i)/2] (or, equivalently x[std::midpoint(i, j)]) where the division rounds towards zero. If a and b do not point to elements of the same array object, the behavior is undefined.
Uses Of midpoint() function:
- Middle point of two integers using midpoint(): Below is the C++ Program to demonstrate the middle point of two integer numbers using midpoint():
C++
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int a = 3;
int b = 6;
cout << "midpoint(" << a << ", "
<< b << "): "
<< midpoint(a, b) << endl;
a = 6;
b = 3;
cout << "midpoint(" << a
<< ", " << b << "): "
<< midpoint(a, b) << endl;
return 0;
}
|
Output:
- midpoint() can handle cases like an overflow: Below is the C++ program to demonstrate how to handle overflow using midpoint():
C++
#include <climits>
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int a = INT_MAX;
int b = INT_MAX - 2;
cout << "a: " << a << endl
<< "b: " << b << endl
<< "Incorrect (overflow"
<< " and wrapping): "
<< (a + b) / 2 << endl
<< "Correct: "
<< midpoint(a, b) << "\n\n" ;
return 0;
}
|
Output:
- Middle point of two floating number using midpoint(): Below is the C++ program to demonstrate how to find the middle point of two floating-point numbers using midpoint():
C++
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
float x = 6.56;
float y = 7.23;
cout << "midpoint(" << x
<< ", " << y << "): "
<< midpoint(x, y) << endl;
x = 2.0;
y = 3.0;
cout << "midpoint(" << x
<< ", " << y << "): "
<< midpoint(x, y)
<< endl
<< endl;
}
|
Output:
- Middle point between two pointers pointing to the same object using midpoint(): Below is the C++ program to demonstrate how to find the middle point of two pointers pointing to the same object using midpoint():
C++
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
char str[] = "GeeksforGeeks" ;
char * str1 = &str[4];
char * str2 = &str[9];
cout << "midpoint('" << *str1
<< "', '" << *str2 << "'): '"
<< *midpoint(str1, str2)
<< "'" << endl;
cout << "midpoint('" << *str2
<< "', '" << *str1 << "'): '"
<< *midpoint(str2, str1)
<< "'" << endl;
}
|
Output:
Share your thoughts in the comments
Please Login to comment...