我很难理解如何将$ 1.17等金额转换为此输出:
我需要使用我可以弄清楚的if语句但是,我遇到的问题是试图让更改数量正确显示。这是我的代码。我是一个视觉学习者,所以如果你从正确的方向开始我将会有所帮助。
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an amount in double, for example 11.56: " );
double number = input.nextDouble();
System.out.println("Your amount " + number + " consists of ");
int Dollars = (int) (number);
int Quarters = Dollars / 25;
if (number == 1) {
System.out.print("1 dollar ");
}
else if (number > 1) {
System.out.print((int)Dollars + " dollars ");
}
if (number == 0) {
System.out.println("");
}
System.out.print( Quarters + " Quarters ");
}
}
答案 0 :(得分:2)
您可能希望使用模数运算符%
。它与2个数字一起使用,并返回余下的a
除以b
,其中a
是左手赋值,b
右手代表{{1} }。
示例:
a%b
解释:11%2=1
,5*2 = 10
11-10 = 1
解释:.66%.25=.16
,2*.25 = .5
从一个简单的问题开始,你只有两种类型的硬币,比如.66-.5=.16
或8¢
。
$0.08
答案 1 :(得分:1)
比使用模数更简单的方法是以自上而下的方式(从最高到最低)计算测量单位,并从已经转换为最低单位的总数中扣除它们
许多图书馆也以 time 的单位使用这种方法,即将时间跨度转换为小时,分钟和秒。这是货币的相同方法。我添加了内联注释以尽可能地解释代码。
// Scan the amount
Scanner scanner = new Scanner(System.in);
System.out.print("Enter amount: ");
double amount = scanner.nextDouble();
scanner.close();
// convert into cents
int cents = (int) (amount * 100);
// get dollars
int dollars = cents/100;
// cents left after dollars
cents = cents - dollars*100;
// get quarters
int quaters = cents/25;
// cents left after quarters
cents = cents - quaters*25;
// get dimes
int dimes = cents/10;
// cents left after dimes
cents = cents - dimes*10;
// get nickels
int nickels = cents/5;
// cents left after nickels
cents = cents - nickels*5;
// leftover cents are pennies
int pennies = cents;
现在,只需使用StringBuilder
StringBuilder msg = new StringBuilder("You have:");
if (dollars > 0) {
msg.append(" ").append(dollars).append(" dollar").append(dollars > 1 ? "s" : "");
}
if (quaters > 0) {
msg.append(" ").append(quaters).append(" quarter").append(quaters > 1 ? "s" : "");
}
if (dimes > 0) {
msg.append(" ").append(dimes).append(" dime").append(dimes > 1 ? "s" : "");
}
if (nickels > 0) {
msg.append(" ").append(nickels).append(" nickel").append(nickels > 1 ? "s" : "");
}
if (pennies > 0) {
msg.append(" ").append(pennies).append(" pennie").append(pennies > 1 ? "s" : "");
}
System.out.println(msg);
输出:
Enter amount: 1.17
You have: 1 dollar 1 dime 1 nickel 2 pennies
Enter amount: 12.99
You have: 12 dollars 3 quarters 2 dimes 4 pennies