C ++ nearint () - biblioteka standardowa języka C ++

Funkcja nearint () w C ++ zaokrągla argument do wartości całkowitej przy użyciu bieżącego trybu zaokrąglania.

Funkcja nearint () w C ++ zaokrągla argument do wartości całkowitej przy użyciu bieżącego trybu zaokrąglania. Bieżący tryb zaokrąglania jest określany przez funkcję fesetround(). Funkcja nearint () jest podobna do rint (), z tą różnicą, że nie zgłasza wyjątków FE_INEXACT jako rint ().

Wyjątek FE_INEXACT to wyjątek zmiennoprzecinkowy, który występuje, gdy wynik operacji nie jest dokładnie reprezentowany z powodu zaokrąglenia lub stopniowego niedomiaru.

nearint () prototyp (w standardzie C ++ 11)

double nearint (podwójne x); float nearint (float x); długie podwójne nearint (długie podwójne x); podwójny pobliskiint (T x); // Dla typu całkowitego

Funkcja nearint () przyjmuje pojedynczy argument i zwraca wartość typu double, float lub long double. Ta funkcja jest zdefiniowana w pliku nagłówkowym.

nearint () Parametry

Funkcja nearint () przyjmuje wartość pojedynczego argumentu do zaokrąglenia.

nearint () Zwraca wartość

Funkcja nearint () zaokrągla argument x do wartości całkowitej, używając kierunku zaokrąglania określonego przez fegetround () i zwraca wartość. Domyślnie kierunek zaokrąglania jest ustawiony na „do najbliższego”. Kierunek zaokrąglania można ustawić na inne wartości za pomocą funkcji fesetround ().

Przykład 1: Jak nearint () działa w C ++?

 #include #include #include using namespace std; int main() ( // by default, rounding direction is to-nearest i.e. fesetround(FE_TONEAREST) double x = 11.87, result; result = nearbyint(x); cout << "Rounding to-nearest (" << x << ") = " << result << endl; // upper value is taken for mid-way values x = 11.5; result = nearbyint(x); cout << "Rounding to-nearest (" << x << ") = " << result << endl; // setting rounding direction to DOWNWARD fesetround(FE_DOWNWARD); x = 17.87; result = nearbyint(x); cout << "Rounding downward (" << x << ") = " << nearbyint(x) << endl; // setting rounding direction to UPWARD x = 33.34; fesetround(FE_UPWARD); result = nearbyint(x); cout << "Rounding upward (" << x << ") = " << result << endl; return 0; )

Po uruchomieniu programu wynik będzie następujący:

 Zaokrąglenie do najbliższego (11,87) = 12 Zaokrąglenie do najbliższego (11,5) = 12 Zaokrąglenie w dół (17,87) = 17 Zaokrąglenie w górę (33,3401) = 34

Przykład 2: funkcja nearint () dla typów całkowitych

 #include #include #include using namespace std; int main() ( int x = 15; double result; // setting rounding direction to DOWNWARD fesetround(FE_DOWNWARD); result = nearbyint(x); cout << "Rounding downward (" << x << ") = " << result << endl; return 0; ) 

Po uruchomieniu programu wynik będzie następujący:

 Zaokrąglanie w dół (15) = 15 

W przypadku wartości całkowitych zastosowanie nearbyintfunkcji zwraca tę samą wartość co dane wejściowe. Dlatego w praktyce nie jest powszechnie używany dla wartości całkowitych.

Interesujące artykuły...