我想製作一個小系統,它返回任何價值的紙幣和硬幣的優化數量。獲取任何價值的紙幣和硬幣的數量
這裏是我的,而代號:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
double amount = Double.parseDouble(br.readLine());
if (amount > 0 && amount < 1000000.00) {
// ############################# BILLS ############################
double rest100 = amount/100;
double rest50 = amount % 100;
double rest20 = rest50 % 50;
double rest10 = rest20 % 20;
double rest5 = rest10 % 10;
double rest2 = rest5 % 5;
// ############################ COINS ############################
double rest01 = rest2 % 2;
double rest050 = rest01 % 1;
double rest025 = rest050 % .5;
double rest010 = rest025 % 25;
double rest005 = rest010 % .1;
double rest001 = rest005 % .05;
System.out.println("BILLS:\n"
+ (int) rest100
+ " bill(s) of 100.00\n"
+ (int) rest50/50
+ " bill(s) of 50.00\n"
+ (int) rest20/20
+ " bill(s) of 20.00\n"
+ (int) rest10/10
+ " bill(s) of 10.00\n"
+ (int) rest5/5
+ " bill(s) of 5.00\n"
+ (int) rest2/2
+ " bill(s) of 2.00\n"
+ "COINS:\n"
+ (int) (rest01/1)
+ " coin(s) of 1.00\n"
+ (int) (rest050/.5)
+ " coin(s) of 0.50\n"
+ (int) (rest025/.25)
+ " coin(s) of 0.25\n"
+ (int) (rest010/.1)
+ " coin(s) of 0.10\n"
+ (int) (rest005/.05)
+ " coin(s) of 0.05\n"
+ (int) (rest001/.01)
+ " coin(s) of 0.01");
}
}
嗯,這是幾乎是正確的,鈔票被工作完美,我的問題是與硬幣。
這裏有一些輸入:
- 576.73 //打印正確
- 8.45 //打印錯誤地
- 9.45 //打印錯誤,看下面:
實際輸出:
BILLS:
0 bill(s) of 100.00
0 bill(s) of 50.00
0 bill(s) of 20.00
0 bill(s) of 10.00
1 bill(s) of 5.00
2 bill(s) of 2.00
COINS:
0 coin(s) of 1.00
0 coin(s) of 0.50
1 coin(s) of 0.25
4 coin(s) of 0.10
0 coin(s) of 0.05
4 coin(s) of 0.01
Expec泰德輸出:
BILLS:
0 bill(s) of 100.00
0 bill(s) of 50.00
0 bill(s) of 20.00
0 bill(s) of 10.00
1 bill(s) of 5.00
2 bill(s) of 2.00
COINS:
0 coin(s) of 1.00
0 coin(s) of 0.50
1 coin(s) of 0.25
2 coin(s) of 0.10
0 coin(s) of 0.05
0 coin(s) of 0.01
PS:我不會發布所有的預期產出,因爲它會讓比現在更大的問題,但如果你需要,我可以張貼。提前致謝。
我懷疑問題出在0.1,0.05,0.01,因爲它們不能精確地表示爲浮點數。考慮使用整數來處理這類問題,因爲整數運算是精確和快速的。 –
你是否在使用math.floor(rest100):?爲什麼你有50美分的硬幣? – kpie
@kpie真的沒有什麼..一個錯誤,但沒關係(不幸)。 50美分的硬幣存在於我的國家。 – developer033