你好,我遇到了这个代码的问题我有一些逻辑,但仍然没有完成,我想假设在1p和500p之间的金额中计算出最小数量的硬币。当我使用500它不打印任何x.x什么我做错了,只有当我输入1或500以上任何帮助将是欣赏
public class exchange{
public static void main(String[] args)
{
int coin;
int OnePound = 0;
int TwoPound = 0;
int FiftyP = 0;
int TwentyP = 0;
int TenP = 0;
int FiveP = 0;
int TwoP = 0;
int OneP = 0;
int Compare = 0;
int Tcoins = 0 ;
System.out.print("#Introduce the amount of Coins");
coin = BIO.getInt();
if (coin < 1 || coin > 500 )
{
System.out.print("Invalid amount "+coin+"p");
}
if (coin == 1)
{
System.out.println("1 coin");
System.exit(1);
}
while (Compare != coin)
{
if ( 200 <= coin && Compare < coin )
{
Compare = Compare + 200;
TwoPound = TwoPound + 1;
Tcoins = Tcoins + 1;
}
if ( 100 <= coin && Compare < coin )
{
Compare = Compare + 100;
OnePound = OnePound + 1;
Tcoins = Tcoins + 1;
}
if ( 50 <= coin && Compare < coin )
{
Compare = Compare + 50;
FiftyP = FiftyP + 1;
Tcoins = Tcoins + 1;
}
if ( 20 <= coin && Compare < coin )
{
Compare = Compare + 20;
TwentyP = TwentyP + 1;
Tcoins = Tcoins + 1;
}
if ( 10 <= coin && Compare < coin )
{
Compare = Compare + 10;
TenP = TenP + 1;
Tcoins = Tcoins + 1;
}
if ( 5 <= coin && Compare < coin )
{
Compare = Compare + 5;
FiveP = FiveP + 1;
Tcoins = Tcoins + 1;
}
if ( 2 <= coin && Compare < coin )
{
Compare = Compare + 2;
TwoP = TwoP + 1;
Tcoins = Tcoins + 1;
}
if ( 1 <= coin && Compare < coin )
{
Compare = Compare + 1;
OneP = OneP + 1;
Tcoins = Tcoins + 1;
}
}
System.out.print("Amount of coins: "+Tcoins);
}
}
答案 0 :(得分:0)
您必须测试运行总和与总数之间的差异:
if ( 200 <= coin - Compare )
{
Compare = Compare + 200;
TwoPound = TwoPound + 1;
Tcoins = Tcoins + 1;
}
else if ( 100 <= coin - Compare )
{
Compare = Compare + 100;
OnePound = OnePound + 1;
Tcoins = Tcoins + 1;
}
所有内容都需要else if
,因为您想尝试较大的值,直到不再适合大值,然后尝试较小的值。