用Java编写一个程序利用do while或for写把从键盘输入的金额数以元为单位按人民币面额划分然后显示支付该金额的各种面额人民币的数量
包括100元、50元、20元、10元、5元、1元。如果输入的金额数小于1元,则直接输出“无法划分”。以下是示例代码:
import java.util.Scanner;
public class RMBDenomination {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入金额数(以元为单位):");
double amount = scanner.nextDouble();
if (amount < 1) {
System.out.println("无法划分");
} else {
int[] denominations = {100, 50, 20, 10, 5, 1};
int[] counts = new int[6];
int index = 0;
do {
int denomination = denominations[index];
counts[index] = (int) (amount / denomination);
amount -= counts[index] * denomination;
index++;
} while (amount > 0 && index < denominations.length);
System.out.println("支付该金额的各种面额人民币的数量如下:");
for (int i = 0; i < counts.length; i++) {
System.out.println(denominations[i] + "元:" + counts[i] + "张");
}
}
}
}
示例输出:
请输入金额数(以元为单位):387.5 支付该金额的各种面额人民币的数量如下: 100元:3张 50元:1张 20元:1张 10元:1张 5元:1张 1元:2
原文地址: https://www.cveoy.top/t/topic/cJJr 著作权归作者所有。请勿转载和采集!