gpt4 book ai didi

java - Java中如何获取金币数量?

转载 作者:行者123 更新时间:2023-12-02 03:58:47 24 4
gpt4 key购买 nike

我有我的代码,用户输入金额,输出显示二十、十、五、一、二十五、二毛五、一毛、镍和便士的数量,但是我希望用户输入硬币数量(例如 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");

}
}

最佳答案

模运算符是你的 friend :

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");
}

关于java - Java中如何获取金币数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35121707/

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