有沒有人有我的輸出問題的想法?奇怪的Java輸出 - 用Eclipse在Mac獅子上運行虛擬機
我已經編寫了一個Java程序,並使用Eclipse在Mac lion上的VM上運行它。 代替1.41
,我在我的機器上得到了1.4100000000000001
。
Example:
Enter the number of quarter: 4
Enter the number of dimes: 3
Enter the number of nickels: 2
Enter the number of pennies: 1
Total $1.4100000000000001
Example:
Enter the number of quarter: 3
Enter the number of dimes: 2
Enter the number of nickels: 1
Enter the number of pennies: 6
Total $1.06
Example:
Enter the number of quarter: 5
Enter the number of dimes: 7
Enter the number of nickels: 4
Enter the number of pennies: 4
Total $2.1900000000000004
有時出現輸出正確,而其他時間有問題。
代碼:
import java.util.*;
public class CountChange
{
public static void main(String[]args)
{
Scanner inputScanner = new Scanner(System.in);
System.out.print("Enter the number of quarters: ");
int quarters = inputScanner.nextInt();
System.out.print("Enter the number of dimes: ");
int dimes = inputScanner.nextInt();
System.out.print("Enter the number of nickles: ");
int nickles = inputScanner.nextInt();
System.out.print("Enter the number of pennies: ");
int pennies = inputScanner.nextInt();
inputScanner.close();
double total =0.00;
total = quarters * 0.25 + dimes * 0.1 + nickles * 0.05 + pennies * 0.01;
System.out.println("Total $" + total);
System.out.print("Thank you");
}
}
http://floating-point-gui.de/ –
如果您使用浮點數,則需要舍入結果。嘗試'System.out.printf(「$%。2f%n「,value);' –