在 C 中使用带有两个正双打的余数将其变为负数?

Using remainder in C with two positive doubles turns it to negative?

我刚开始学习 C 编程,但每当我 运行 这个:

double a = 9.92; 
double b = 2.00;
printf("%.2lf,  %.2lf,  %.2lf", a, b, remainder(a, b));

输出总是$-0.18。我希望的输出是 1.92 美元。

余数函数将除法结果四舍五入为最接近的整数,这意味着您可以获得负数结果。来自手册页:

The remainder() function computes the remainder of dividing x by y. The return value is x-n*y, where n is the value x / y, rounded to the nearest integer. If the absolute value of x-n*y is 0.5, n is chosen to be even.

根据您的输入,9.92 / 2 结果为 4.96,四舍五入为最接近的整数 5。那么你有 9.92 - (5 * 2.00) == 9.92 - 10.0 == -0.08.

您想改为使用 fmod,它将除法四舍五入到 0。该手册页指出:

The fmod() function computes the floating-point remainder of dividing x by y. The return value is x - n * y, where n is the quotient of x / y, rounded toward zero to an integer.