我是高中的初中。經歷一段艱難的時間才搞清楚如何使用金錢格式。我正在練習Java編程指南(第二版),我必須提示員工提供漢堡包,薯條和蘇打水的數量。資金格式 - 我如何使用它?
薯條是$ 1.09,漢堡包是$ 1.69,蘇打水是$ 0.99。
這裏是我的代碼:
import java.util.Scanner;
/**
* Order pg. 101
*
* Garret Mantz
* 2/10/2016
*/
public class Order {
public static void main(String[]args) {
final double pburgers=1.69;
final double pfries=1.09;
final double psodas=0.99;
final double ptax=0.065;
double burgers;
double fries;
double sodas;
double totaltax;
double total;
double tax;
double tendered;
double change;
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of burgers: ");
burgers = input.nextDouble();
System.out.print("Enter the amount of fries: ");
fries = input.nextDouble();
System.out.print("Enter the amount of sodas: ");
sodas = input.nextDouble();
System.out.print("Enter the amount tendered: ");
tendered = input.nextDouble();
totaltax = (burgers*pburgers)+(fries*pfries)+(sodas*psodas);
tax = totaltax*ptax;
total = totaltax + tax;
change = tendered - total;
System.out.println("Your total before tax is: \n" + totaltax);
System.out.println("Tax: \n" + tax);
System.out.println("Your final total is: \n" + total);
System.out.println("Your change is: \n" + change);
}
}
我只是想用錢的格式,但我不知道怎麼樣。我確定這是一個愚蠢的問題,但謝謝你的幫助!
剛擡起頭,你應該**從不**使用浮點數來存儲貨幣。格式以二進制形式存儲數據,以便將其表示爲某個無符號二進制整數(有效數)* 2的一些冪。因爲它存儲在兩個而不是十個的權力,你可能會遇到很多麻煩。相反,使用定點方法(例如,將美分數存儲在「長」中)[更多閱讀](https://en.wikipedia.org/wiki/Floating_point) –