6 Ağustos 2020 Perşembe

std::fesetround metodu

Giriş
Açıklaması şöyle. float veya double bir tipine integral (int gibi) bir tipe çevrilirken ne yöne yuvarlanacağını belirtir.
Since C++11, one can use fesetround(), the floating-point environment rounding direction manager. There are four standard rounding directions and an implementation is permitted to add additional rounding directions.
Bu değerler şöyle FE_DOWNWARD,FE_TONEAREST,FE_TOWARDZERO,FE_UPWARD

Bu metodu kullanırken bir sebepten #pragma kullanmak lazım. Açıklaması şöyle
Don't forget about #pragma STDC FENV_ACCESS ON, otherwise this has undefined behavior.
Örnek
Şöyle yaparız
#include <cfenv> // for fesetround() and FE_* macros
#include <iostream> // for cout and endl
#include <iomanip> // for setprecision()

#pragma STDC FENV_ACCESS ON

int main(){
 int i = 2147483647;

 std::cout << std::setprecision(10);

 std::fesetround(FE_DOWNWARD);
 std::cout << "round down " << i << " :  " << static_cast<float>(i) << std::endl;
 std::cout << "round down " << -i << " : " << static_cast<float>(-i) << std::endl;

 std::fesetround(FE_TONEAREST);
 std::cout << "round to nearest " << i << " :  " << static_cast<float>(i) << std::endl;
 std::cout << "round to nearest " << -i << " : " << static_cast<float>(-i) << std::endl;

 std::fesetround(FE_TOWARDZERO);
 std::cout << "round toward zero " << i << " :  " << static_cast<float>(i) << std::endl;
 std::cout << "round toward zero " << -i << " : " << static_cast<float>(-i) << std::endl;

  std::fesetround(FE_UPWARD);
  std::cout << "round up " << i << " :  " << static_cast<float>(i) << std::endl;
  std::cout << "round up " << -i << " : " << static_cast<float>(-i) << std::endl;

  return(0);
}
Çıktı olarak şunu alırız
round down         2147483647 :  2147483520
round down        -2147483647 : -2147483648
round to nearest   2147483647 :  2147483648
round to nearest  -2147483647 : -2147483648
round toward zero  2147483647 :  2147483520
round toward zero -2147483647 : -2147483520
round up           2147483647 :  2147483648
round up          -2147483647 : -2147483520

Hiç yorum yok:

Yorum Gönder