【发布时间】:2017-04-20 22:09:17
【问题描述】:
我的代码应该计算总组合。使用这些硬币支付 1-500 美元之间的现金:1、2、5、10、20、50、100、200。但它计算不正确。我做错了什么? 您可以假设输入是正确的,并且您只能使用循环和 if 语句。你不能使用递归。
int pr, a, b, c, d, e, f, g,h, poss = 0;
printf_s("What is the amount that you like to check? (or press '0' to exit)\n");
scanf_s("%d", &pr);
for (a = 0; a <= pr; a++)
{
for (b = 0; b <= (pr/2); b++)
{
for (c = 0; c <= (pr /5); c++)
{
for (d = 0; d <= (pr /10); d++)
{
for (e = 0; e <= (pr /20); e++)
{
for (f = 0; f <= (pr / 50); f++)
{
for (g = 0; g <= (pr / 100); g++)
{
for (h = 0; h <= (pr/200); h++)
{
if (1 * a + 2 * b + 4 * c + 10 * d + 20 * e + 40 * f + 100 * g + h * 200 == pr)
poss += 1;
}
}
}
}
}
}
}printf_s("The number of possibilities is: %d.\n", poss);
}
【问题讨论】:
-
结果如何?您的程序是否多次打印它?
-
将
printf语句移出循环后,输入100 需要一秒钟才能报告6118。输入 200 需要 45 秒才能报告104342。所以我的猜测是 500 将持续到明天,这个数字将超出int的范围。
标签: c loops for-loop combinations