remaining()在if语句C ++中不起作用

问题描述 投票:1回答:1

下面的代码应该输出每个第10个术语(0.0,10.0,20.0等等)直到100.0。但它只输出“0”。有谁知道这是什么问题?

include <iostream>
include <cmath>
using namespace std;

for (double t = 0.0; t < 100.0; t += 0.1)
{
    if (remainder(t, 10.0) == 0)
    {
        cout << t << "\n";
    }
}
c++11
1个回答
2
投票

您正在处理具有固有不准确性的浮点数。 remainder返回一个浮点值并使用==将值精确地检查为0并不总是有效。

您需要使用公差并查看余数是否在公差的范围内:

#include <iostream>
#include <cmath>

int main()
{
    for (double t = 0.0; t <= 100.0; t += 0.1)
    {
        if (std::abs(std::remainder(t, 10.0)) <= 0.001)
        {
            std::cout << t << "\n";
        }
    }
}

注意:further reading

© www.soinside.com 2019 - 2024. All rights reserved.