我的代码应该计算总组合。使用这些硬币支付 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);
}
最佳答案
当输入 5
时,会报告正确的权限数,但展开代码会打印错误的值。因为这一行
if (1 * a + 2 * b + 4 * c + 10 * d + 20 * e + 40 * f + 100 * g + h * 200 == pr)
面额错误。应该是
if (1 * a + 2 * b + 5 * c + 10 * d + 20 * e + 50 * f + 100 * g + h * 200 == pr)
你还应该移动这条线
printf_s("The number of possibilities is: %d.\n", poss);
在循环之外。
关于c 8个硬币组合代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43530739/