名前空間
変種
操作

std::midpoint

提供: cppreference.com
< cpp‎ | numeric
ヘッダ <numeric> で定義
template< class T >
constexpr T midpoint(T a, T b) noexcept;
(1) (C++20以上)
template< class T >
constexpr T* midpoint(T* a, T* b);
(2) (C++20以上)

整数、浮動小数点、またはポインタ ab の中点を計算します。

1) このオーバーロードは、 Tbool 以外の算術型である場合にのみ、オーバーロード解決に参加します。
2) このオーバーロードは、 T はオブジェクト型である場合にのみ、オーバーロード解決に参加します。 T不完全型である場合、このオーバーロードは ill-formed です。

目次

[編集] 引数

a, b - 整数、浮動小数点、またはポインタの値

[編集] 戻り値

1) ab の和の半分。 オーバーフローは発生しません。 ab が整数型で、その和が奇数の場合、結果は a に向かって丸められます。 ab が浮動小数点型の場合、不正確な演算は多くとも1回しか発生しません。
2) ab が、それぞれ、 (ポインタ算術の目的のために) 同じ配列オブジェクト xx[i]x[j] ��指している場合、 x[i+(j-i)/2] を指すポインタを返します (除算はゼロに向かって丸められます)。 ab が同じ配列オブジェクトの要素を指していない場合、動作は未定義です。

[編集] 例外

何も例外を投げません。

[編集]

#include <cstdint>
#include <limits>
#include <numeric>
#include <iostream>
 
int main()
{
    std::uint32_t a = std::numeric_limits<std::uint32_t>::max();
    std::uint32_t b = std::numeric_limits<std::uint32_t>::max() - 2;
 
    std::cout << "a: " << a << '\n'
              << "b: " << b << '\n'
              << "Incorrect (overflow and wrapping): " << (a + b) / 2 << '\n'
              << "Correct: " << std::midpoint(a, b) << '\n';
}

出力:

a: 4294967295
b: 4294967293
Incorrect (overflow and wrapping): 2147483646
Correct: 4294967294