我有我的代码,用户输入一定数量的金额,输出显示二十,十,五,一,四分之一,硬币,镍币和便士的数量,但我想要用户输入一定数量的硬币(例如36)并获得36美分的仅限硬币的数量。这意味着我应该得到1分,1分和1分。请有人帮我这个。非常感谢!
注意:
DecimalFormat类不是必需的
这是我的代码:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Compu
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
DecimalFormat decimalFormat = new DecimalFormat("0.00");
System.out.println("Please Enter an amount of Money:");
double change = input.nextDouble();
int dollars = (int)change;
int twenties = dollars / 20;
int dollars1 = dollars % 20;
int tens = dollars1 / 10;
int dollars2 = dollars % 10;
int fives = dollars2 / 5;
int dollars3 = dollars % 5;
int ones = dollars3;
String moneyString = decimalFormat.format(change);
String changeString = Double.toString(change);
String[] parts = moneyString.split("\\.");
String part2 = parts[1];
double cents5 = Double.parseDouble(part2);
int cents = (int)cents5;
int quarters = cents / 25;
int cents1 = cents % 25;
int dimes = cents1 / 10;
int cents2 = cents % 10;
int nickels = cents2 / 5;
int cents3 = cents % 5;
int pennies = cents3;
System.out.println("Input entered by user: " + "$" + moneyString);
System.out.println(twenties + " Twenties");
System.out.println(tens + " Tens");
System.out.println(fives + " Fives");
System.out.println(ones + " Ones");
System.out.println(quarters + " Quarters");
System.out.println(dimes + " Dimes");
System.out.println(nickels + " Nickels");
System.out.println(pennies + " Pennies");
}
}
答案 0 :(得分:1)
模数运算符是你的朋友:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount in cents");
double cents = input.nextInt();
int numQuarters = cents / 25;
int numDimes = (cents % 25) / 10;
int numNickels = ((cents % 25) % 10) / 5;
int numPennies = ((cents % 25) % 10) % 5;
System.out.println(quarters + " Quarters");
System.out.println(dimes + " Dimes");
System.out.println(nickels + " Nickels");
System.out.println(pennies + " Pennies");
}
答案 1 :(得分:1)
为此,请完全删除处理美元的程序部分,并将用户输入直接输入'美分'。
此外,这部分:
int cents = (int)cents5;
int quarters = cents / 25;
int cents1 = cents % 25;
int dimes = cents1 / 10;
int cents2 = cents % 10;
int nickels = cents2 / 5;
int cents3 = cents % 5;
int pennies = cents3;
不准确(在少数情况下。并非全部),因为您没有更改'美分'的值。因此,如果输入'36',它将返回1个四分之一(25),1个角钱(35),1个镍(40)和1个便士(41)。
要避免这种情况,请使用以下代码:
int cents = (int)cents5;
int quarters = cents / 25;
int cents1 = cents % 25;
int dimes = cents1 / 10;
int cents2 = cents1 % 10;
int nickels = cents2 / 5;
int cents3 = cents2 % 5;
int pennies = cents3;