C++: std::remquo 没有给出预期的输出

C++: std::remquo not giving expected output

我试图在 C++ 中找出一个 double 分成另一个 double 的次数,我发现这样做的唯一函数是 remquo。但是当使用它时,它并没有给出预期的结果,结果商只在 0 和 3 之间,而它们应该在 0 到 20 之间。

更小的双精度数是否可以使用更精确的浮点数?

int quotient;
    double remainder = remquo((coordX+maxX), tileSizeX, &quotient);
    cout << coordX+maxX << " / " << tileSizeX << " = " << quotient << " r " << remainder << endl;
    return quotient;

在这种情况下,maxX 将为 0.773,coordX 将为 -0.773 到 0.773 之间的数字,最后 tileSizeX 约为 0.073619。

这里是 cout 调用的一些输出:

0.773 / 0.073619 = 2 r 0.0368095 但是 0.073619 * 2 + 0.0368095 = 0.1840475,远不及我预期的 0.773。

0.085 / 0.073619 = 0 r 0.011381 <- 错误

0.181 / 0.073619 = 2 r 0.0337619 <- 右

0.433 / 0.073619 = 3 r -0.00871429 <- 错误

1.269 / 0.073619 = 0 r 0.0174762 <- 错误

余数似乎总是正确的,但商几乎从来都不是。有什么我不明白的吗。

remquo的定义包括(C11 7.12.10.3/1, C++17引用):

The remquo functions compute the same remainder as the remainder functions. In the object pointed to by quo they store a value whose sign is the sign of x/y and whose magnitude is congruent modulo 2n to the magnitude of the integral quotient of x/y, where n is an implementation-defined integer greater than or equal to 3.

您似乎错误地期望 quo 保留积分商的实际值。


I am trying to find the number of times one double divides into another in C++

有多种方法可以做到这一点,例如std::trunc(x/y)std::lrint(x/y)。阅读 std::remainderstd::fmod 的文档也可能会有帮助。您可以在 cppreference.com 或 ISO C 和 C++ 草稿中查找所有这些函数。