gpt4 book ai didi

java - java中int到double的转换

转载 作者:行者123 更新时间:2023-11-30 03:47:38 25 4
gpt4 key购买 nike

以下代码计算自动售货机分配的零钱。我的问题?我无法让更改变量工作,因为由于两种不同的数据类型(int 和 double 转换),编译器不允许我工作。谁能帮我解决这个问题。我尝试过类型转换“change”,但它不会打印正确的数量。例如,如果变化是 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");
}
}


}

最佳答案

您应该在任何地方使用整数,但以美分而不是美元来计算。打印时只需将数字除以 100 即可。

这是因为 float double 无法准确表示用于货币的以10为基数的倍数,并且会引入舍入误差,特别是在相乘计算利率时。

参见Why not use Double or Float to represent currency?了解更多信息和讨论。

关于java - java中int到double的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25228455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com