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

前端 未结 2 1092
醉梦人生
醉梦人生 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: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

提交回复
热议问题