這個程序的工作原理,除非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);
}
}
因爲它看起來像是作業,所以我只給出一個提示:*使用DecimalFormat類。* – 2012-01-17 13:24:11
使用Java提供的類有什麼問題?這不是任何第三方課程。 – 2012-01-17 13:28:04
重複的http://stackoverflow.com/questions/8819842/best-way-to-format-a-double-value-to-2-decimal-places – 2012-01-17 13:29:39