Java, item store discount math error

This program is designed to act as a store where numbers are entered for the corresponding items and quantities The problem is that if you need three or more items, you will get a 10% discount on your purchase and should truncate any decimals (keep in the integer range of int data type) The program will run, but no discount will be calculated, and the program will always be displayed as 0 Look at this!

int item,longsword,shortsword,warhammer,ring,potion,itemcost,quantity,discount,totalcost,finalcost;

    System.out.print("Item Number: ");
    item = keyboard.nextInt();

    final int LONGSWORD = 120;
    final int SHORTSWORD = 90;
    final int WARHAMMER = 80;
    final int RING = 150;
    final int POTION = 10;

    itemcost = 0;

    if (item == 1)
    {
        itemcost = LONGSWORD;
    }

    if (item == 2)
    {
        itemcost = SHORTSWORD;
    }   

    if (item == 3)
    {
        itemcost = WARHAMMER;
    }   

    if (item == 4)
    {
        itemcost = RING;
    }

    if (item == 5)
    {
        itemcost = POTION;
    }

    System.out.print("Quantity of Item: ");
    quantity = keyboard.nextInt();  

    totalcost = itemcost * quantity;

    System.out.println("Total Cost: " + totalcost);

    if (quantity >= 3)
    {
        discount = totalcost * (1/10);
    }

    else
    {
        discount = 0;
    }

    System.out.println("Discount: " + discount);

Solution

You have encountered such a common integer division problem

discount = totalcost * (1/10);

1 / 10 is 0, so the discount is 0 Use this instead of:

discount = (int) (totalcost * (0.1));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>