gpt4 book ai didi

java - 如何计算硬币的数量?

转载 作者:行者123 更新时间:2023-12-01 22:33:52 25 4
gpt4 key购买 nike

您好,我正在学习 Java,并正在编写代码来将输入的便士数量转换为零钱。

因此,如果我输入 439p,它会打印:439p 2*200p 4*100p 1*20p 1*10p 1*5p 4*1p。我需要实现的最后一件事是在打印语句中包含总共有多少个硬币

所以在这种情况下,它应该打印为:439p 13 个硬币 2*200p 4*100p 1*20p 1*10p 1*5p 4*1p。我知道这可能很简单,但我真的不知道如何做到这一点,因此我们将不胜感激:)

我的代码是

class Main { 
public static void main( String args[] ) {

System.out.print("#Please enter the amount of change : ");
int change = BIO.getInt();

while(change > 0)
{
int twopounds, pounds, fifty, twenty, ten, five, two, one;

twopounds = change / 200;
int left = change % 200;

pounds = change / 100;
left = change % 100;

fifty = left / 50;
left = left % 50;

twenty = left / 20;
left = left % 20;

ten = left / 10;
left = left % 10;

five = left / 5;
left = left % 5;

two = left / 2;
two = left % 2;

one = left / 1;

if (change == 1)
{
System.out.print("1 coin");
}

if (change > 500)
{
System.out.print("Invalid amount " + change + "p" + "\n");
}

if (change <= 500 && change > 1)

System.out.print(change + "p ");
{
if ( twopounds > 0 )
{
System.out.print( twopounds > 0 ? twopounds + "*200p " : "" );
}

if ( pounds > 0 )
{
System.out.print( pounds > 0 ? pounds + "*100p " : "" );
}

if ( fifty > 0 )
{
System.out.print( fifty > 0 ? fifty + "*50p " : "" );
}

if ( twenty > 0 )
{
System.out.print( twenty > 0 ? twenty + "*20p " : "" );
}

if ( ten > 0 )
{
System.out.print( ten > 0 ? ten + "*10p " : "" );
}

if ( five > 0 )
{
System.out.print( five > 0 ? five + "*5p " : "" );
}

if ( two > 0 )
{
System.out.print( two > 0 ? two + "*2p " : "" );
}

if ( one > 0 )
{
System.out.print( one > 0 ? one + "*1p " : "" );
}
}
System.out.print("#Please enter the amount of change : ");
change = BIO.getInt();
}

}

最佳答案

很简单:

int nbCoins = twopounds + pounds + fifty + twenty + ten + five + two + one

关于java - 如何计算硬币的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27173167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com