admin管理员组

文章数量:1558072

第四章第二十六题(金融应用:货币单位)(Financial application: monetary units)

  • *4.26(金融应用:货币单位)重写程序清单2-10,解决将float型值转换为int型值时可能会造成精度损失的问题。读取的输入值是一个字符串,比如“11.56”。你的程序应该应用indexOf和substring方法提取小数点前的美元数量,以及小数点后的美分数量。
    *4.26(Financial application: monetary units) Rewrite Listing 2.10, ComputeChange.java, to fix the possible loss of accuracy when converting a float value to an int value. Read the input as a string such as “11.56”. Your program should extract the dollar amount before the decimal point, and the cents after the decimal amount using the indexOf and substring methods.
  • 参考代码:
package chapter04;

import java.util.Scanner;

public class Code_26 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter an amount in double, for example 11.56: ");
        String amount = input.nextLine();

        int remainingAmount = (int)(Integer.parseInt(amount.substring(0, amount.indexOf('.'))) * 100
                + Integer.parseInt(amount.substring(amount.indexOf('.')+1)));

        int numberOfOneDollars = remainingAmount / 100;
        remainingAmount = remainingAmount % 100;

        // Find the number of quarters in the remaining amount
        int numberOfQuarters = remainingAmount / 25;
        remainingAmount = remainingAmount % 25;

        int numberOfDimes = remainingAmount / 10;
        remainingAmount = remainingAmount % 10;

        int numberOfNickels = remainingAmount / 5;
        remainingAmount = remainingAmount % 5;

        int numberOfPennies = remainingAmount;

        System.out.println("Your amount " + amount + " consists of");
        System.out.println(" " + numberOfOneDollars + " dollars");
        System.out.println(" " + numberOfQuarters + " quarters ");
        System.out.println(" " + numberOfDimes + " dimes");
        System.out.println(" " + numberOfNickels + " nickels");
        System.out.println(" " + numberOfPennies + " pennies");

        input.close();
    }
}

  • 结果显示:
Enter an amount in double, for example 11.56: 11.56
Your amount 11.56 consists of
 11 dollars
 2 quarters 
 0 dimes
 1 nickels
 1 pennies

Process finished with exit code 0

本文标签: 第四章第二十六货币单位金融