构建硬币组合 c# 代码(开始循环)
Constructing the coins combination c# code (beginning the loops)
我正在尝试解决这个任务:"Having a coins of 1, 2, and 5 $, check for how many possible ways you will be able to get out of these coins combinations the sum of 10$"
我找不到好的解决方案,因为我的代码显示只有 7 种组合。谁能帮我纠正一下思路和代码?
int combination_amount = 0;
int cash_amount = 10;
int a , b , c;
for (a = 0; a < 10; a++)
{
for (b = 0; b < 5; b++)
{
for (c = 0; c < 2; c++)
{
if (1 * a + 2 * b + 5 * c == 10)
{
combination_amount += 1;
}
}
}
}
Console.WriteLine("There is a total number of {0} combinations amount ", combination_amount);
问题出在你的for
循环的退出条件,你使用“<”,这意味着它将不包括限制值,因此你会缺少诸如“5 乘以 2”之类的解决方案。
用“<=”而不是“<”重写你的循环,你应该得到正确的值。
我正在尝试解决这个任务:"Having a coins of 1, 2, and 5 $, check for how many possible ways you will be able to get out of these coins combinations the sum of 10$"
我找不到好的解决方案,因为我的代码显示只有 7 种组合。谁能帮我纠正一下思路和代码?
int combination_amount = 0;
int cash_amount = 10;
int a , b , c;
for (a = 0; a < 10; a++)
{
for (b = 0; b < 5; b++)
{
for (c = 0; c < 2; c++)
{
if (1 * a + 2 * b + 5 * c == 10)
{
combination_amount += 1;
}
}
}
}
Console.WriteLine("There is a total number of {0} combinations amount ", combination_amount);
问题出在你的for
循环的退出条件,你使用“<”,这意味着它将不包括限制值,因此你会缺少诸如“5 乘以 2”之类的解决方案。
用“<=”而不是“<”重写你的循环,你应该得到正确的值。