C++ 中的rint() 函數使用當前舍入模式將參數舍入為整數值。
C++ 中的rint() 函數使用當前舍入模式將參數舍入為整數值。當前舍入模式由函數fesetround() 確定。
rint() 原型 [從 C++ 11 標準開始]
double rint(double x); float rint(float x); long double rint(long double x); double rint(T x); // For integral type
rint() 函數采用單個參數並返回 double、float 或 long double 類型的值。該函數在<cmath> 頭文件中定義。
參數:
rint() 函數采用單個參數值進行舍入。
返回:
rint() 函數使用 fegetround() 指定的舍入方向將參數 x 舍入為整數值並返回該值。默認情況下,舍入方向設置為'to-nearest'。可以使用fesetround() 函數將舍入方向設置為其他值。
示例 1:rint() 如何在 C++ 中工作?
#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;
int main()
{
// by default, rounding direction is to-nearest i.e. fesetround(FE_TONEAREST)
double x = 11.87, result;
result = rint(x);
cout << "Rounding to-nearest (" << x << ") = " << result << endl;
// upper value is taken for mid-way values
x = 11.5;
result = rint(x);
cout << "Rounding to-nearest (" << x << ") = " << result << endl;
// setting rounding direction to DOWNWARD
fesetround(FE_DOWNWARD);
x = 11.87;
result = rint(x);
cout << "Rounding downward (" << x << ") = " << result << endl;
// setting rounding direction to UPWARD
fesetround(FE_UPWARD);
x = 33.32;
result = rint(x);
cout << "Rounding upward (" << x << ") = " << result << endl;
return 0;
}
運行程序時,輸出將是:
Rounding to-nearest (11.87) = 12 Rounding to-nearest (11.5) = 12 Rounding downward (11.8699) = 11 Rounding upward (33.3201) = 34
示例 2:用於整數類型的 rint() 函數
#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;
int main()
{
int x = 15;
double result;
// setting rounding direction to DOWNWARD
fesetround(FE_DOWNWARD);
result = rint(x);
cout << "Rounding downward (" << x << ") = " << result << endl;
return 0;
}
運行程序時,輸出將是:
Rounding downward (15) = 15
對於整數值,應用 rint 函數返回與輸入相同的值。所以在實踐中它並不常用於整數值。
相關用法
- C++ rint(), rintf(), rintl()用法及代碼示例
- C++ regex_iterator()用法及代碼示例
- C++ rotate用法及代碼示例
- C++ remainder()用法及代碼示例
- C++ remquo()用法及代碼示例
- C++ ratio_less_equal()用法及代碼示例
- C++ rename()用法及代碼示例
- C++ rewind()用法及代碼示例
- C++ ratio_less()用法及代碼示例
- C++ round()用法及代碼示例
- C++ raise()用法及代碼示例
- C++ ratio_greater()用法及代碼示例
- C++ ratio_not_equal()用法及代碼示例
- C++ remove()用法及代碼示例
- C++ ratio_greater_equal()用法及代碼示例
- C++ realloc()用法及代碼示例
- C++ ratio_equal()用法及代碼示例
- C++ rename用法及代碼示例
- C++ real()用法及代碼示例
- C++ unordered_map cbegin用法及代碼示例
注:本文由純淨天空篩選整理自 C++ rint()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。