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

    科技2022-07-10  144

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

    *2.22(金融应用:货币单位)改写程序清单2-10,解决将double型值转换为int型值可能会造成精度损失问题。以整数值作为输入,其最后两位代表的是美分币值。例如:1156就表示的是11美元56美分。 *2.22(Financial application: monetary units) Rewrite Listing 2.10, ComputeChange. java, to fix the possible loss of accuracy when converting a double value to an int value. Enter the input as an integer whose last two digits represent the cents. For example, the input 1156 represents 11 dollars and 56 cents.参考代码: package chapter02; import java.util.Scanner; public class Code_22 { public static void main(String[] args) { Scanner Input = new Scanner(System.in); System.out.print("Enter an amount in Int,for example 1156:"); int amount = Input.nextInt(); int remainingAmount = amount; int numberOfOneDollars = remainingAmount / 100; remainingAmount %= 100; int numberOfQuarters = remainingAmount / 25; remainingAmount %= 25; int numberOfDimes = remainingAmount / 10; remainingAmount %= 10; int numberOfNickels = remainingAmount / 5; 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 Int,for example 1156:1156 Your amount 1156 consists of 11 dollars 2 quarters 0 dimes 1 nickels 1 pennies Process finished with exit code 0
    Processed: 0.013, SQL: 8