我有足够的钱去工作,但现在我不知道如何正确显示宿舍,角钱,镍币和便士。从技术上讲,它们出现了,但我的教授希望1.35美元显示1美元1个季度和1个角钱。但是,我的显示为1美元5季度13角钱27镍135便士。这是我的代码:

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 remainingamount = (int)(number*100);
        int Quarters = remainingamount/25;
        int Dimes = remainingamount/10;
        int Nickels = remainingamount/5;
        int Pennies = remainingamount;

        if (number == 1) {
            System.out.print("1 dollar ");
        }
        else if (number > 1) {
            System.out.print((int)number + " dollars ");
        }
        if (number == 0) {
            System.out.println("");
        }
        System.out.print(Quarters + " Quarters " + Dimes + " Dimes " + Nickels + " Nickels " + Pennies + " Pennies");
    }
}

最佳答案

对于您计算的每个不同硬币,您需要将其从剩余金额中删除。如(未测试):

    int Dollars = (int)number;
    int remainingamount = (int)((number-Dollars)*100);
    int Quarters = remainingamount/25;
    remainingamount -= Quaters * 25;
    int Dimes = remainingamount/10;
    remainingamount -= Dimes * 10
    int Nickels = remainingamount/5;
    remainingamount -= Nickels * 5
    int Pennies = remainingamount;

关于java - 转换货币单位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28624396/

10-10 20:41