C中贪心算法中的浮点数问题

Floating point issue in greedy algorithm in C

尽管我知道还有其他线程与此相关,但我已经创建了自己的线程,因为我不想看到其他人的解决方案。除了 4.2 之外,所有结果打印都很好。我知道浮点不精确并试图解决它,但无法解决。

有人能指出我正确的方向吗? (没有解决方案,只是朝着正确的方向点头。)

#include<stdio.h>
#include<cs50.h>
#include<math.h>

int main(void)
{
    double quarter = 0.250, dimes = 0.100, nickels = 0.050, pennies = 0.010;
    double $change = 0.00;
    int coins = 0;
    double rem = 0.00;
    double rem2 = 0;
    double rem3 = 0;
    double a = 0;
    int b = 0;
    double c = 0;
    double d = 0;

    do
    {
        $change = get_float("Change owed: ");
    }
    while( $change < 0);
    int cents = round( $change * 100);

    a = $change / quarter;
    rem = fmod($change, quarter);

    b = rem / dimes;
    rem2 = fmod(rem, dimes);

    c = rem2 / nickels;
    rem3 = fmod(rem2, nickels);

    d = rem3 / pennies;

    coins = a + b + c + d;

    printf("%i\n", coins);
    return 0;
}

不要使用 floats/doubles Why not use Double or Float to represent currency?

例如,您可以使用最小数量为 1 便士的整数。您可以将所有内容转换为便士以进行计算,然后您可以将其转换回任何内容以显示为,但您应该始终对待提醒,例如某些部分可以有额外的便士。或者,如果您想要更通用的解决方案,那么也许您可以使用小数,例如 https://github.com/libdfp/libdfp and How to print/convert decimal floating point values in GCC?

您可以搜索更多https://github.com/search?l=C&q=decimal&type=Repositories