Java,项目商店折扣数学错误
发布时间:2020-12-15 04:46:05 所属栏目:Java 来源:网络整理
导读:该程序旨在充当商店,其中输入数字以用于相应的项目和数量.问题在于,如果您需要三个或更多项目,您将获得购买的10%折扣,并且应截断任何小数(保持在int数据类型的整数范围内).程序将运行,但不计算折扣,并且程序将运行时始终显示为0.看看这个! int item,longsw
该程序旨在充当商店,其中输入数字以用于相应的项目和数量.问题在于,如果您需要三个或更多项目,您将获得购买的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,因此折扣为0.使用此代替: discount = (int) (totalcost * (0.1)); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |