如何限制为双精度值打印的小数位数?
这个程序有效,除非nJars的数量是7的倍数,否则我会得到一个像$ 14.999999999999998这样的答案。对于 6,输出为 14.08。如何修复 7 的倍数的异常,使其显示类似 14.99 美元的内容?
import java.util.Scanner;
public class Homework_17
{
private static int nJars, nCartons, totalOunces, OuncesTolbs, lbs;
public static void main(String[] args)
{
computeShippingCost();
}
public static void computeShippingCost()
{
System.out.print("Enter a number of jars: ");
Scanner kboard = new Scanner (System.in);
nJars = kboard.nextInt();
int nCartons = (nJars + 11) / 12;
int totalOunces = (nJars * 21) + (nCartons * 25);
int lbs = totalOunces / 16;
double shippingCost = ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;
System.out.print("$" + shippingCost);
}
}