首页 > 解决方案 > 如何在 C 中使用特定(不规则)步骤进行循环?

问题描述

我在 C 中为贪心算法编写了以下函数('change' 和 'numberCoins' 是全局变量)。

int calculateNumber(void)
{
    numberCoins += change / 25;
    change = change % 25;

    numberCoins += change / 10;
    change = change % 10;

    numberCoins += change / 5;
    change = change % 5;

    numberCoins += change / 1;
    change = change % 1;

    return 0;
} 

它工作正常。但是,复制和粘贴让我感到不安。有没有可能在不重复的情况下写出来?我的想法是循环编写它。但我不知道如何用不规则的步骤进行循环。我的想法看起来像这样(我是如何做到的,我在第一次迭代中被分配了 25,然后是 15,然后是 10,然后是 1)?

for (int i = 25; i >= 5; ???)
    {
        numberCoins += change / i;
        change = change % i;
    }

感谢您的帮助。

标签: cfor-loop

解决方案


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/87c8d7


推荐阅读