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

前端 未结 2 1066
醉梦人生
醉梦人生 2021-01-29 12:30

EDIT: After re-writing my code in my IDE, for the 8th time today, I have made rookie mistake of giving my inputs a false data type, that has been fixed but my outputs still are

相关标签:
2条回答
  • 2021-01-29 13:19

    Here's the problem: There are 4 loops, one for quarters, one for dimes, one for nickels, and one for pennies. The first loop condition is correct:

    while (cents >= 25)
    

    The other three are incorrect:

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

    These all need to be changed to use >= in place of >.

    0 讨论(0)
  • 2021-01-29 13:34

    you can do it much simple for any nominals. Use integer types.

    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

    0 讨论(0)
提交回复
热议问题