第一章课后习题1.3
1.3 只使用处理I/O的printDigit方法,编写一种方法以输出任意double型量(可以是负值)。
package com.algorithm.chapterone; /** * 只使用处理I/O的printDigit方法,编写一种方法以输出任意double型量(可以是负值) * @author Gao·Rongzheng * */ public class QuestionThree { public static void main(String[] args) { // TODO Auto-generated method stub double num = -12.63; if (num < 0) { System.out.print("-"); num = Math.abs(num); } int integer = (int) num; int integerLength = Integer.toString(integer).length(); int decimalLength = Double.toString(num).length() - integerLength - 1; printDigit(num, -integerLength, decimalLength); } public static void printDigit(double num, int integerLength, int decimalLength) { //※ 递归方法的的基准 if (integerLength == decimalLength) { return; } //※ 往基准靠拢 integerLength++; int n = (int) (num * Math.pow(10, integerLength)); System.out.print(n % 10); //※ 判断输出小数 if (integerLength == 0) { System.out.print("."); } printDigit(num, integerLength, decimalLength); } }