在C++中,round()
函數(shù)用于將一個浮點數(shù)四舍五入為最接近的整數(shù)。它的作用是將浮點數(shù)值取整,返回最接近的整數(shù)值,返回類型為double。round()
函數(shù)的原型如下:
double round(double x);
x
:要四舍五入的浮點數(shù)。round()
函數(shù)的工作原理如下:
x
的小數(shù)部分小于0.5,則round()
函數(shù)將向下取整(舍去小數(shù)部分)。x
的小數(shù)部分大于或等于0.5,則round()
函數(shù)將向上取整(進位到下一個整數(shù))。下面是幾個round()
函數(shù)的示例:
#include <iostream>
#include <cmath>
int main() {
double x = 3.7;
double y = 4.3;
std::cout << "Round of " << x << " is " << round(x) << std::endl; // 輸出:Round of 3.7 is 4
std::cout << "Round of " << y << " is " << round(y) << std::endl; // 輸出:Round of 4.3 is 4
return 0;
}
在上面的例子中,round(x)
將3.7四舍五入為4,round(y)
將4.3四舍五入為4。