温馨提示×

c++中round函数的作用是什么

c++
小亿
95
2024-01-27 13:17:18
栏目: 编程语言

在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。

0