第二章第二十二题(金融应用:货币单位)(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.

下面是参考答案代码:

import java.util.*;

public class MonetaryUnitsQuestion22 {
	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();
	}
}

运行效果:
第二章第二十二题(金融应用:货币单位)(Financial application: monetary units)_第1张图片

注:编写程序要养成良好习惯
如:1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)

你可能感兴趣的:(#,第二章课后习题答案)