C++ 中的 round()。
C++ 中的 round() 函数用于将传递给它作为参数的 double、float 或 long double 值四舍五入到最近的整数。用于在 c++ 程序中使用 round() 函数的头文件是 <cmath> 或 <tgmath>。
以下是 C++ 11 标准之后的 round() 的重载版本
- double round( double D )
- float round( float F )
- long double round( long double LD )
- double round ( T var )
注意 - 返回的值是最近的整数,表示为浮点数,即对于 2.3,返回的最近值将是 2.0 而不是 2。
以下程序用于演示在 C++ 程序中使用 round 函数 -
示例
#include <cmath> #include <iostream> int main(){ double num1=10.5; double num2=10.3; double num3=9.7; std::cout << "Nearest integer after round("<<num1<<") :" << round(num1)<< "\n"; std::cout << "Nearest integer after round("<<num2<<") :" << round(num2)<< "\n"; std::cout << "Nearest integer after round("<<num3<<") :" << round(num3)<< "\n"; num1=-9.3; num2=-0.3; num3=-9.9; std::cout << "Nearest integer after round("<<num1<<") :" << round(num1)<< "\n"; std::cout << "Nearest integer after round("<<num2<<") :" << round(num2)<< "\n"; std::cout << "Nearest integer after round("<<num3<<") :" << round(num3)<< "\n"; return 0; }
输出
Nearest integer after round(10.5) :11 Nearest integer after round(10.3) :10 Nearest integer after round(9.7) :10 Nearest integer after round(-9.3) :-9 Nearest integer after round(-0.3) :-0 Nearest integer after round(-9.9) :-10
广告