C ++中的Round()在哪里? [英] Where is Round() in C++?

查看:654
本文介绍了C ++中的Round()在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我使用的是VS2008,我已经包含math.h但是我还是找不到圆函数。它存在吗?

I'm using VS2008 and I've included math.h but I still can't find a round function. Does it exist?

我在google上看到一堆add 0.5 and cast to int解决方案。

I'm seeing a bunch of "add 0.5 and cast to int" solutions on google. Is that the best practice?

推荐答案

您可以使用C ++ 11的 std :: round()

You may use C++11's std::round().

如果您仍然使用旧版标准,可以使用 std :: floor() (总是舍入到较低的数字)和 std :: ceil() ,总是舍入到更高的数字。

If you are still stuck with older standards, you may use std::floor(), which always rounds to the lower number, and std::ceil(), which always rounds to the higher number.

正常的舍入行为,你会使用 floor(i + 0.5)

To get the normal rounding behaviour, you would indeed use floor(i + 0.5).

负数,该问题的解决方法是使用ceil()用于负数:

This way will give you problems with negative numbers, a workaround for that problem is by using ceil() for negative numbers:

double round(double number)
{
    return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}

另一种更干净,更耗资源的方法是使用stringstream和输入/输出操纵器:

Another, cleaner, but more resource-intensive, way is to make use of a stringstream and the input-/output-manipulators:

#include <iostream>
#include <sstream>

double round(double val, int precision)
{
    std::stringstream s;
    s << std::setprecision(precision) << std::setiosflags(std::ios_base::fixed) << val;
    s >> val;
    return val;
}

只有在资源不足和/或需要控制时才使用第二种方法精度。

Only use the second approach if you are not low on resources and/or need to have control over the precision.

这篇关于C ++中的Round()在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆