2013-09-26 88 views
-1

目前我正在嘗試在java中編寫更改機器。出於某種原因,轉換過程中準確度有很大的損失。奇準確度錯誤Java

它會首先詢問欠款多少和付多少的數據值。然後它將劃分宿舍的數量並修改其餘部分。然後它會用硬幣,鎳幣,然後便士來執行此操作。之後,它會打印出多少變化。

import java.io.*; 
import static java.lang.System.*; 

import java.util.Scanner; 

class change{ 


    public static void main (String str[]) throws IOException { 

      //asker thingy 
      Scanner scan = new Scanner(System.in); 
      System.out.println("Please enter the Cost of the Item:"); 
      System.out.print("$"); 
      double costowed = scan.nextDouble(); 
      System.out.println("Please Enter the Amount Payed:"); 
      System.out.print("$"); 
      double costpayed = scan.nextDouble(); 

      //Quarters 
      double a1 = Math.round((costpayed - costowed) * 100); 
      int quarters = (int)(a1/25); 
      int a2 = (int)(a1 % 25); 

      //dimes 
      int dimes = (int)(a2/10); 
      int a3 = (int)(a1 % 10); 

      //nickles & pennies 
      int nickles = (int)(a3/5); 
      int pennies = (int)(a1 % 5); 

      //change owed 
      double arc = (double)(a1/100); 

      //print sequence 
      System.out.println("Change owed: " + arc); 
      System.out.println("Quarters: " + quarters); 
      System.out.println("Dimes: " + dimes); 
      System.out.println("Nickles: " + nickles); 
      System.out.println("Pennies: " + pennies); 
    } 

} 
+3

首先 - 究竟是什麼問題?其次,我建議你使用BigDecimal來賺錢。 –

+0

只是一個方面的說明,但你不需要包括這些的加利福尼亞或to魚呢?關於改變的法案呢?或者,如果支付的金額和物品價格之間的差距很大,你是否只給出了一個萬億的收入? –

+1

@ miss.serena - 這是一個兩位操作,最多隻有四分之一的變化。 –

回答

1

int a3 = (int)(a1 % 10); 

應該是:

int a3 = (int)(a2 % 10); 

而且同樣int pennies = (int)(a1 % 5);應該int pennies = (int)(a3 % 5);