我正在编写一个代码,该代码将从标准输入中读取一个实数为两倍,然后获取该值并打印出最少的纸币和硬币以达到该数量。我不确定如何在必要时将代码打印成一定数量的代码。如果有人可以鸣叫,我将不胜感激!
import java.util.Scanner;
import java.lang.Math;
public class Changecalc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter amount) ");
double amount = input.nextDouble();
int amountInt = (int) (amount * 100);
double tmp;
if(amount >= 100)
{
tmp = (int) amount/100;
System.out.println (tmp + "$100 bills");
amount = amount % 100;
}
if(amount >= 50)
{
tmp = (int) amount/50;
System.out.println (tmp + "$50 bills");
amount = amount % 50;
}
if(amount >= 20)
{
tmp = (int) amount/50;
System.out.println (tmp + "$20 bills");
amount = amount % 20;
}
if(amount >= 10)
{
tmp= (int) amount/50;
System.out.println (tmp + "$10 bills");
amount = amount % 10;
}
if(amount >= 5)
{
tmp = (int) amount/5;
System.out.println (tmp + "$5 bills");
amount = amount % 5;
}
if(amount >= 1)
{
tmp = (int) amount/1;
System.out.println (tmp + "$1 bills");
amount = amount % 1;
}
if(amount >= .25)
{
tmp = (int) amount/.25;
System.out.println (tmp + "quater");
amount = amount % .25;
}
if(amount >= .10)
{
tmp = (int) amount/.10;
System.out.println (tmp + "dime");
amount = amount % .10;
}
if(amount >= .05)
{
tmp = (int) amount/.05;
System.out.println (tmp + "nickel");
amount = amount % .05;
}
if(amount >= .01)
{
tmp = (int) amount/.01;
System.out.println (tmp + "penny");
amount = amount % 01;
}
}
}
最佳答案
您的代码大部分是正确的。只是当金额> = 20时,
if(amount >= 20)
{
tmp = (int) amount/50;
System.out.println (tmp + "$20 bills");
amount = amount % 20;
}
相反,它应该是
if(amount >= 20)
{
tmp = (int) amount/20;
System.out.println (tmp + "$20 bills");
amount = amount % 20;
}
类似的问题是当金额> = 10时。您需要将其更正为
好。
除此之外,您还需要具有打印一张或多张钞票的逻辑(如果有多个钞票),并且对四分之一硬币,一角硬币,镍币和便士/小笔有类似的逻辑
对于复数,您可以使用类似于以下内容
if(amount >= 100){
tmp = (int) amount/100;
if(tmp > 1.0){
System.out.println (tmp + "$100 bills");
} else{
System.out.println (tmp + "$100 bill");
}
amount = amount % 100;
}
关于java - Java更改计算器输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32815658/