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
版权声明:本文标题:第四章第二十六题(金融应用:货币单位)(Financial application: monetary units) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1727384137a1112224.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论