c - 如何在 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;
}
感谢您的帮助。
解决方案
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]);
}
}
推荐阅读
- android - 我在我的项目中使用 Fragments 和带有 TabLayout 的 ViewPager,它没有在设备上运行
- asp.net - 多次返回视图或如何动态更新视图
- sql - SQL:根据布尔值更改 SELECT 的结果
- c# - 创建字符串表.net C#
- php - PHP 的“回声”无法正常工作
- qt - 从 Qt4 移植到 Qt5,Qt::WA_PaintOutsidePaintEvent 不再存在
- batch-file - 批处理文件计算器除法余数
- laravel - Laravel 5.6 版注册错误
- reactjs - 目标创意的 Adwords API 未提供某些关键字的平均每次点击费用和覆盖面
- mysql - 如果查询相同,则不计算 MariaDB 性能模式摘要