2017-09-05 84 views
1

所以我被分配到寫一個程序,提示用戶,併爲雙讀取輸入的數值(最大輸入爲[99.99] 99美元,99美分),我的編程類,這將代表一筆金額。我然後確定最少數量的各鈔票和硬幣來代表所述量所需的(10美元的鈔票是所需的最大尺寸)。Java的貨幣面額四捨五入問題

我遇到四捨五入的問題。例如,輸入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"); 

    } 

} 
+2

我總是用金錢計算的整數。將價值表示爲美分。 100將是1美元。 – JJF

+0

謝謝!我繼續前進,只是將inputAmount變量轉換爲分,並解決了所有問題! –

回答

0

你會好起來的轉換數字爲整數(硬幣的量)和計算基礎上,作爲這樣就可以避免浮點錯誤,你現在正在經歷的類型(它們是造成由浮點數表示爲二進制)

如果通過使用this步驟(您需要硬編碼輸入使用它),你可以看到錯誤。

的變化量作爲設置由於98.99999999999949 20行四捨五入,所以這就是爲什麼一分錢去失蹤

+0

感謝您的幫助!我繼續,只是根據什麼@JJF說過轉換的inputAmount分錢,然後轉換該金額爲整數。之後,我只需要將所有美元面值的因素乘以100,這似乎解決了所有問題。 –