编写一段java程序,实现从控制台中读取一个数字,然后打印出这个数字四舍五入后对应的人民币大写汉字字符。例如: 输入:3000 输出:叁仟 输入:300.569 输出:三佰元五角七分
时间: 2023-02-06 20:52:19 浏览: 72
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("请输入一个数字: ");
double num = scan.nextDouble();
String[] str = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
String[] unit1 = {"", "拾", "佰", "仟"};
String[] unit2 = {"", "万", "亿"};
String result = "";
int z = 0;
while (num > 0) {
int n = (int) (num % 10);
if (n != 0) {
result = str[n] + unit1[z] + result;
} else {
if (result.length() > 0 && result.charAt(0) != '零') {
result = str[n] + result;
}
}
num /= 10;
z++;
if (z == 4) {
z = 0;
num /= 10000;
result = unit2[0] + result;
}
}
if (result.length() == 0) {
result = "零";
}
System.out.println("人民币大写: " + result + "元");
}
}
程序的思路是: 使用 Scanner 类读取控制台输入的数字, 然后用一个循环不断取出数字的最后一位, 并转化为对应的人民币大写汉字字符. 在循环的过程中, 还需要记录当前数位(个位, 十位, 百位, 千位, 万位, 亿位)并加上对应的单位(如: 十, 百, 千, 万, 亿). 最后将所有字符拼接在一起就可以得到最终的结果.