在C++中,round()函數用于將一個浮點數四舍五入為最接近的整數。它的作用是將浮點數值取整,返回最接近的整數值,返回類型為double。round()函數的原型如下:
double round(double x);
x:要四舍五入的浮點數。round()函數的工作原理如下:
x的小數部分小于0.5,則round()函數將向下取整(舍去小數部分)。x的小數部分大于或等于0.5,則round()函數將向上取整(進位到下一個整數)。下面是幾個round()函數的示例:
#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。