[英]Converting from int to double in java
以下代碼計算自動售貨機分配的零錢。 我的問題? 由於兩種不同的數據類型(整數和雙精度轉換),編譯器不允許我使用更改變量,因此無法正常工作。 誰能幫我解決這個問題。 我已經嘗試過投放“更改”,但隨后無法打印正確的金額。 例如,如果找零是0.25美分,則找零值當然會保持零。 問題開始於第16行。我已將示例給出的部分注釋為change = 0.25。
public String[] itemList = new String[] {"Water ","Coke ", "Diet Coke", "Iced Tea","Fanta "};
public double[] priceList = new double[] {75,120, 120, 100, 150};
public int[] itemQty = new int[]{10,10,10,10,10};
public int[] coinList = new int[]{100,50,20,10,5};
public int[] coinQty = new int[]{10,10,10,10,10};
public double change;
public double paid;
public void ReturnChange()
{
int Denominations=5;
int coins_dispensed = 0 ;
int[] InitialArray = new int[Denominations];
//My Problem begins here..for example if change is computed
change = 0.25; //change is a global declaration of type double and carries values derived from different function
int change1 = (int)change; //if i cast here, i get change as 0, thus the part that follows, fails to compute coins dispensed.
for (int i=0; i < 5; i++)
{
InitialArray[i] += coinQty[i]; // Copies Coin Quantity to Initial array for difference
}
System.out.println("Your change is "+NumberFormat.getCurrencyInstance().format(Math.abs(change1)) +" which comprises of:"); //OK till here
for (int i=0; i<5; i++)
{
if (coinQty[i]>0) //if a particular denomination is available
{
coins_dispensed = (change1/coinList[i]); //dividing coins dispense with denomination
coinQty[i] -= coins_dispensed; //reduce the quantity of the denomination dispensed
change1 = change1 - (coinList[i] * coins_dispensed); //total the change
}
else // Moves to next denomination if a particular coin runs out
{
coins_dispensed = (change1/coinList[i+1]);
coinQty[i+1] -= coins_dispensed ;
change1 = change1 - (coinList[i+1] * coins_dispensed);
}
}
if (change1 != 0) // In the case not enough coins to make change, selection is ignored.
{
System.out.println("\n\n\t Sorry. The machine doesnt have enough coins to make up your change. Your last transaction has been ignored.");
}
else
{
for (int i=0; i<Denominations; i++)
{
coins_dispensed = InitialArray[i] - coinQty[i];
System.out.println( "\n\t\t\t" + coins_dispensed +" of "+ coinList[i] + " cents coins");
}
}
}
您應該在各處使用integers
,但要以美分而非美元為單位。 打印時,只需將數字除以100。
這是因為floats
和doubles
數不能准確表示用於貨幣的基數10的倍數,並且會引入舍入誤差,尤其是在乘以例如計算利率時。
請參閱為什么不使用Double或Float表示貨幣? 有關更多信息和討論。
看來您的所有變量都以美分持有價格(我想可樂不是120美元)。 但是您的找零顯然用美元指定。 因此,您可以做的是將更改乘以100,然后將其強制轉換為int 。
像那樣:
int change1 = (int) (change * 100); // convert dollars to cents and cast to int
如果在某個時候需要以美元(而不是美分)輸出change1,則必須將其轉換回:
float result = change1 / 100.0f;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.