简体   繁体   English

在Java中从int转换为double

[英]Converting from int to double in java

the following code calculates change dispensed by a vending machine. 以下代码计算自动售货机分配的零钱。 My problem? 我的问题? I cant get the change variable to work as the compiler wont let me due to two different data types (int & double conversion). 由于两种不同的数据类型(整数和双精度转换),编译器不允许我使用更改变量,因此无法正常工作。 Can anyone please help me solve this problem. 谁能帮我解决这个问题。 I have tried casting "change" but then it wont print right amount. 我已经尝试过投放“更改”,但随后无法打印正确的金额。 For example, if the change is 0.25 cents, change value remains zero..for obvious reasons of course. 例如,如果找零是0.25美分,则找零值当然会保持零。 The problem begins at line 16. I have commented the part giving example as 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");
        }
    }


}

You should use use integers everywhere but count in cents not dollars. 您应该在各处使用integers ,但要以美分而非美元为单位。 Just divide your numbers by 100 when you print them. 打印时,只需将数字除以100。

This is because floats and doubles cannot accurately represent the base 10 multiples used for money and will introduce rounding errors, particularly when multiplying to calculate interest rates for example. 这是因为floatsdoubles数不能准确表示用于货币的基数10的倍数,并且会引入舍入误差,尤其是在乘以例如计算利率时。

See Why not use Double or Float to represent currency? 请参阅为什么不使用Double或Float表示货币? for more information and discussion. 有关更多信息和讨论。

It seems all your variables hold prices in cents (i guess a coke is not 120 $). 看来您的所有变量都以美分持有价格(我想可乐不是120美元)。 But your change is apparently specified in dollars. 但是您的找零显然用美元指定。 So what you could do is multiply change by 100 and then cast it to int . 因此,您可以做的是将更改乘以100,然后将其强制转换为int

Like that: 像那样:

int change1 = (int) (change * 100); // convert dollars to cents and cast to int

If you need to output change1 in dollars (and not cents) at some point, you have to convert it back: 如果在某个时候需要以美元(而不是美分)输出change1,则必须将其转换回:

float result = change1 / 100.0f;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM