我正在使用 Java,但是它没有正确添加金额。我将给出我的部分代码。
final double taxrate=.08;
Map<String,Integer> Priceproduct= new HashMap<String,Integer>();
Priceproduct.put("shoes",(int) 50.00);
Priceproduct.put("shirts",(int) 30.00);
Priceproduct.put("shorts",(int) 75.00);
Priceproduct.put("caps",(int) 15.00);
Priceproduct.put("jackets",(int) 100.00);
System.out.print("\n Enter the product: ");
String product=keyboard.nextLine();
System.out.print( "\n Enter the quantity of the product");
int quantity=keyboard.nextInt();
int cost= Priceproduct.get(product)*quantity;
int tax= (int) (cost*taxrate);
System.out.print("\n tax=" +cost*taxrate+"");
int TotalBill= cost+tax;
System.out.print("\nTotal="+cost+ + +tax+"");
当它加上成本和税收(这两个是正确的)时,它会得到完全错误的答案。 例如 3 件衬衫= 90,税收等于 7.2,总计变为 907。
我需要使用 DecimalFormat 还是其他格式?
最佳答案
更改此:
System.out.print("\nTotal="+cost+ + +tax+"");
对此:
System.out.println();
System.out.print("Total=" + (cost + tax));
(问题是 +
是左关联的,因此如果添加时没有括号,"a"+ b + c
表示 ("a"+ b) + c
,在两个阶段进行字符串连接。)
关于java - 为什么添加的变量是错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22263831/