【JAVA 第三章 流程控制语句】课后习题 找零钱

知识点:
数组 循环 的理解与运用
懵懵懂懂 需要加强练习!

public static void main(String[] args) {
        boolean i=true;
        double dscan=0;//存储键入的金额
        int intOfdscan=0;//存储金额的整数
        String[] str = {"百 元","五十元","二十元","十 元","五 元","一 元","五 毛","一 毛","一分"};
        int[] money = {10000,5000,2000,1000,500,100,50,10,1};
        int[] pics =new int[money.length];//存储张数

        System.out.println("请输入您需要找零的金额:");
        while (i){
            Scanner scan = new Scanner(System.in);
            try {
                 dscan = scan.nextDouble();
                i=false;
            } catch (Exception e) {
                System.out.println("您的输入有误,请重新输入!");
            }
        }
        //将含有小数的零钱化为整数 万位既是 百 千位 十 百位 元 十位数既是 角 个位数 既是 分
        intOfdscan = (int)(dscan*100);
        //定义一个for长度为money的循环
        for (int j = 0; j< money.length;j++){
            //将金额与币值相比较 大于等于 表示 条件成立进入循环
            while (intOfdscan >= money[j]){
                //将金额与币值相减 一次pic累加一张,然后继续循环 直到条件不成立
                intOfdscan -= money[j];
                pics[j]++;
            }
            //控制输出 零张的 不输出
            if (pics[j] != 0){
                System.out.println(pics[j]+"\t张\t"+str[j]);
            }
        }


    }

猜你喜欢

转载自blog.csdn.net/weixin_43933620/article/details/91493750