因此,我被分配为编程类编写一个程序,该程序提示用户并以双精度形式(最大输入为[99.99]九十九美元和九十九美分)读取输入的值,这将代表一个金额。然后,我要确定代表上述金额所需的每张钞票和硬币的最少数量(10美元的钞票是所需的最大尺寸)。

我在取整方面遇到问题。例如,输入99.99将返回3便士,而应为4便士。老师明确地告诉我,不要超出课堂讨论的内容(仅涉及创建扫描器,转换数据类型和强制转换。这意味着没有BigDecimal)。任何帮助,将不胜感激。

import java.util.Scanner;

public class MoneyConversion
{
     public static void main(String[] args)
     {
          //Set variables for input, dollars, and cents
          double inputAmount, change;
          int tens, fives, ones;
          int quarters, dimes, nickels, pennies;

          //Create scanner to setup for user input
          Scanner scan = new Scanner(System.in);

          //Scan user input and store into double
          System.out.print("Enter monetary amount: ");
          inputAmount = scan.nextDouble();

          //Extract demical or cent amount from dollar amount
          change = (inputAmount - (int) inputAmount) * 100;

          System.out.println("That's equivalent to:");

          //Extract and print denomination for ten-dollar bills
          tens = (int) inputAmount / 10;
          inputAmount = inputAmount % 10;
          System.out.println(tens + " ten dollar bills");

          //Extract and print denomination for five-dollar bills
          fives = (int) inputAmount / 5;
          inputAmount = inputAmount % 5;
          System.out.println(fives + " five dollar bills");

          //Extract and print denomination for one-dollar bills
          ones = (int) inputAmount;
          System.out.println(ones + " one dollar bills");

          //Extract and print denomination for quarters
          quarters = (int) change / 25;
          change = change % 25;
          System.out.println(quarters + " quarters");

          //Extract and print denomination for dimes
          dimes = (int) change / 10;
          change = change % 10;
          System.out.println(dimes + " dimes");

          //Extract and print denomination for nickels
          nickels = (int) change / 5;
          change = change % 5;
          System.out.println(nickels + " nickels");

          //Convert value for change to integer value and print for pennies
          pennies = (int) change;
          System.out.println(pennies + " pennies");

     }

}

最佳答案

您最好将数字转换为整数(便士的数量)并据此进行计算,因为这样可以避免您现在遇到的浮点错误类型(它们是由浮点数表示为二进制)。

如果逐步使用this(您需要对输入进行硬编码才能使用它),则可以看到错误。

由于在第20行四舍五入,所以更改量设置为98.99999999999949,因此这就是一分钱缺失的原因

10-04 20:22