1.3输出任意实数

public class test {

    public static void printDigit(int n){
        System.out.print(n);
    }
    
    public static void printInt(int n){
        if(n>=10){
            printInt(n/10);
        }
        printDigit(n%10);
    }
    public static int getInt(double n){
        return (int)n;
    }
    public static double getFraction(double n){
        return (n-(int)n);
    }
    public static void printFraction(double fraction,int dec){
        int i,tmp;
        for(i=0;i<dec;i++){
            fraction = fraction *10;
            tmp = getInt(fraction);
            printDigit(tmp);
            fraction = getFraction(fraction);
        }
    }
    public static double runUp(double n,int dec){
        int i;
        double tmp = 0.5;
        for(i =0;i<dec;i++){
            tmp = tmp / 10;
        }
        return (n + tmp);
    }
    public static void printReal(double n,int dec){
        int tmp1;
        double tmp2;
        if(n<0)
            n = -n;
        n = runUp(n,dec);
        tmp1 = getInt(n);
        tmp2 = getFraction(n);
        printInt(tmp1);
        if(dec > 0){
            System.out.print(".");
            printFraction(tmp2,dec);
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        printReal(4.65,2);
    }
}

注意:runUp函数,否则和输出的不一定对。

posted on 2015-03-28 16:00  爱踢小菜  阅读(125)  评论(0编辑  收藏  举报

导航