Java,商品商店折扣数学错误

标签 java math command-prompt discount

该程序旨在充当商店,输入相应商品的编号和数量。要注意的是,如果您想要三件或更多商品,您可以在购买时享受 10% 的折扣,并且任何小数点都应该被截断(保持在 int 数据类型的整数范围内)。该程序将运行,但是不会计算折扣并且始终表示为 0,尽管该程序将运行。检查一下!

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);

最佳答案

您遇到了非常常见的整数除法问题。

discount = totalcost * (1/10);

1/10 为 0,因此 discount 将为 0。请改为使用:

discount = (int) (totalcost * (0.1));

关于Java,商品商店折扣数学错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30559616/

相关文章:

command-line - 如何在批处理文件中创建 OR 语句?

java - 无法使用 Runtime 或 ProcessBuilder 执行排序命令

bash - 将 ANSI 颜色转义序列添加到 bash 提示符会导致在调用/编辑命令时光标位置错误

java - System.currentTimeMillis() 是否返回 UTC 时间?

iphone - 当球撞击轨道时如何获得碰撞效果或弹力

c++ - 四元数相机。如何使其正确旋转?

java - 两个 3D vector 之间的角度

java - Eclipse 在调试期间自行更改变量

java - 当前不支持公式映射 - Hibernate ORM Envers

Java 正则表达式 : Require zero/even amount of backslashes without including backslashes in the match