简体   繁体   English

C ++ floor()将值减1

[英]C++ floor() decreasing value by 1

I wrote this function to recursively round a double to N digits: 我编写了此函数,以将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);
    }
}

But as from the log file, something really strange is happening with floor() in some cases... 但是从日志文件来看,在某些情况下floor()确实发生了一些奇怪的事情……

Here's an output example of good calculation: 这是良好计算的输出示例:

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

And here's an output example of bad calculation: 这是错误计算的输出示例:

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

Isn't floor(6770) supposed to return 6770? floor(6770)是否应该返回6770? Why is it returning 6769? 为什么返回6769?

So first of all thanks everyone for the suggestions. 因此,首先感谢大家的建议。 Btw for the moment the "double to string -> string to double -> floor" solution seems to be the only one giving exactly the expected result. 顺便说一句,“双倍于字符串->字符串至双重->底线”的解决方案似乎是唯一给出预期结果的解决方案。 So i just needed to replace: 所以我只需要替换:

double floored = floor(sum);

with

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

If anyone has a better solution please post it. 如果有人有更好的解决方案,请发布它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM