运行结果
不知道为什么2.28 进去之后就会丢失0.01
package com.xiaoz.classTest;
import java.util.Scanner;
public class Class009 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入美元(小数点后面最多有两位):");
double money = sc.nextDouble();
int rp = remainingPenny(money); // rp : remainingPenny 剩余一分钱
// int rp = remainingPenny(2.28);
System.out.println("剩下一分币的个数为:" + rp);
}
private static int remainingPenny(double money) {
// 将美元转换成分 1美元 = 100分
int rp = (int) ((money) * 100);
boolean flag = true;
while (flag) {
// rp : remainingPenny 剩余一分钱
if (rp >= 100) {
// 1美元
rp = moneyCon(rp, 100);
flag = judgeMoneyZero(rp);
} else if (rp >= 25 && rp < 100) {
// 2角5分
rp = moneyCon(rp, 25);
flag = judgeMoneyZero(rp);
} else if (rp >= 10 && rp < 25) {
// 1角币
rp = moneyCon(rp, 10);
flag = judgeMoneyZero(rp);
} else if (rp >= 5 && rp < 10) {
// 5分币
rp = moneyCon(rp, 5);
flag = judgeMoneyZero(rp);
} else {
// 剩下1分币的个数
flag = false;
}
}
return rp;
}
// 判读当前剩下的币是否为0 如果为0,结束while循环
private static boolean judgeMoneyZero(int rp) {
if (rp == 0) {
return false;
} else {
return true;
}
}
// 计算剩下 1分币
private static int moneyCon(int rp, int rate) {
rp -= (rp / rate) * rate;
return rp;
}
}