c++ - 四舍五入的值(value)

标签 c++ double rounding ostream

在搜索到我的问题的答案后,我决定提出问题。

我被告知我需要将 double 的值四舍五入到小数点后 3 位。

我需要用这个:

os.setf(std::ios::fixed,std::ios::floatfield);
os.precision(3);

所以我知道我需要创建一个 ostream 类型的对象,所以我这样写:

ostream os;
os.setf(std::ios::fixed,std::ios::floatfield);
os.precision(3);
double a = 3.12364;
os << a;

但是有一个编译错误所以我把第一行改成:

ostream os(NULL);

然后编译器关闭了,但我知道它什么也没做。 那么如何使用 ostream 舍入值?

注意我不想打印。我不需要/不想使用 cout

最佳答案

如果您真的不想将结果保存在字符串中,您可以使用简单的数学方法。

#include <cmath>

float myRound(float input) {
    return input > 0
        ? floor(input * 1000 + 0.5) / 1000
        : ceil(input * 1000 + 0.5) / 1000;
}

但请注意,如果乘以 1000 导致溢出,结果将不正确。在 C++11 中,您还可以使用 std::round .

关于c++ - 四舍五入的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14274765/

相关文章:

c# - 不同的类型转换行为

Javascript 在将数字相加时删除小数

C++/Win32 : XP Visual Styles - no controls are showing up?

c++ - 如何使用整数参数访问结构列表 (c++)?

c++ - 每个应用程序实例超过一个 Audio Session

c++ - 如何确定流程的完整性级别?

c++ - double 存储什么?

java - 通过 Try 和 Catch block 检查字符串和 Null 异常

jquery - javascript 将值四舍五入到小数点后两位

swift - 快速舍入数字