无法弄清楚如何在 while 循环中正确地递增变量,C

Cannot figure out how to properly increment a variable inside of a while loop, C

编辑:今天第 8 次在我的 IDE 中重写我的代码后,我犯了新手错误,即为我的输入提供了错误的数据类型,该错误已得到修复,但我的输出仍然是不正确。

关于我的目标的详细信息:进行找零时,您很可能希望尽量减少为每位顾客分配的硬币数量。 好吧,假设收银员欠顾客一些零钱,收银员的抽屉里有 25 美分硬币 (25 美分)、10 美分硬币 (10 美分)、5 美分硬币 (5 美分) 和便士 (1 美分) 硬币。要解决的问题是决定将哪些硬币以及每个硬币的数量交给客户。

预期结果:
欠零钱:0.41
4个

实际结果:
欠零钱:0.41
3

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

int main (void)

{
    float dollars;
    int changeowed = 0;

    do
    {
      dollars = get_float ("Change owed: ");
    }
    while (dollars < 0);

    float cents = round(dollars * 100);

    while (cents >= 25)
    {
        cents = cents - 25;
        changeowed++;
    }

    while (cents > 10)
    {
        cents = cents - 10;
        changeowed++;
    }
    while (cents > 5)
    {
        cents = cents - 5;
        changeowed++;
    }

        while (cents > 1)
        {
            cents = cents - 1;
            changeowed++;
        }

        printf("%i \n", changeowed);
}

问题来了:有 4 个循环,一个用于四分之一,一个用于一角硬币,一个用于镍币,一个用于便士。第一个循环条件正确:

while (cents >= 25)

另外三个不正确:

while (cents > 10)
while (cents > 5)
while (cents > 1)

这些都需要更改为使用 >= 代替 >

对于任何标称值,您都可以简单地做到这一点。使用整数类型。

int nominals[] = {100, 25, 10, 5, 1, 0};

void getNominals(double money, int *result)
{
    unsigned ncents = money * 100.0;
    int *nm = nominals;
    while(*nm && ncents)
    {
        *result++ = ncents / *nm;
        ncents %= *nm++;
    }
}

int main(void)
{
    int result[sizeof(nominals) / sizeof(nominals[0])] = {0};

    getNominals(4.36, result);

    for(size_t index = 0; nominals[index]; index++)
    {
        printf("%d = %d\n", nominals[index], result[index]);
    }
}

https://godbolt.org/z/WdYxxr