C ++ floor()将值减1

时间:2014-02-19 14:07:48

标签: c++ floor

我写了这个函数来递归地将double舍入到N位:

double RoundDouble(double value, unsigned int digits)
{
    if (value == 0.0)
        return value;
    string num = dtos(value);
    size_t found = num.find(".");
    string dec = "";
    if (found != string::npos)
        dec = num.substr(found + 1);
    else
        return value;
    if (dec.length() <= digits)
    {
        LogToFile("C:\\test.txt", "RETURN: " + dtos(value) + "\n\n\n");
        return value;
    }
    else
    {
        double p10 = pow(10, (dec.length() - 1));
        LogToFile("C:\\test.txt", "VALUE: " + dtos(value) + "\n");
        double mul = value * p10;
        LogToFile("C:\\test.txt", "MUL: " + dtos(mul) + "\n");
        double sum = mul + 0.5;
        LogToFile("C:\\test.txt", "SUM: " + dtos(sum) + "\n");
        double floored = floor(sum);
        LogToFile("C:\\test.txt", "FLOORED: " + dtos(floored) + "\n");
        double div = floored / p10;
        LogToFile("C:\\test.txt", "DIV: " + dtos(div) + "\n-------\n");
        return RoundDouble(div, digits);
    }
}

但是从日志文件中,在某些情况下,floor()会发生一些非常奇怪的事情......

以下是良好计算的输出示例:

VALUE: 2.0108
MUL: 2010.8
SUM: 2011.3
FLOORED: 2011
DIV: 2.011
-------
VALUE: 2.011
MUL: 201.1
SUM: 201.6
FLOORED: 201
DIV: 2.01
-------
RETURN: 2.01

以下是错误计算的输出示例:

VALUE: 67.6946
MUL: 67694.6
SUM: 67695.1
FLOORED: 67695
DIV: 67.695
-------
VALUE: 67.695
MUL: 6769.5
SUM: 6770
FLOORED: 6769 <= PROBLEM HERE
DIV: 67.69
-------
RETURN: 67.69

楼层(6770)不应该返回6770吗?为什么它会返回6769?

1 个答案:

答案 0 :(得分:0)

首先,感谢大家的建议。 顺便说一下,“double to string - &gt; string to double - &gt; floor”解决方案似乎是唯一一个给出完全预期结果的解决方案。 所以我只需要替换:

double floored = floor(sum);

double floored = floor(stod(dtos(sum)));

如果有人有更好的解决方案,请发布。