2018/12/06 L1-029 是不是太胖了 Java

考察Java小数点的运算:

总共有四种方案:

1、System.out.printf() 或

2、DecimalFormat

3、System.out.print(String.format("%.1f", flnalNum));

4、NumberFormat


1、使用System.out.printf()的方案, 代码如下:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        double num = Integer.parseInt(br.readLine());
        double finalNum = 0;
        if(num > 100 && num <=300) {
            finalNum = (num-100)*0.9*2;
            System.out.printf("%.1f", finalNum);
        } else {
            return;
        }

    }

}

2、使用DecimalFormat方案:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;

public class Main2 {

    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        double num = Integer.parseInt(br.readLine());
        double finalNum = 0;
        DecimalFormat df = new DecimalFormat("#.0");
        if(num > 100 && num <=300) {
            finalNum = (num-100)*0.9*2;
//            System.out.printf("%.1f", finalNum);
            System.out.print(df.format(finalNum));
        } else {
            return;
        }

    }

}

 

3、System.out.print(String.format("%.1f", flnalNum));方案

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main3 {

    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        double num = Integer.parseInt(br.readLine());
        double finalNum = 0;
        if(num > 100 && num <=300) {
            finalNum = (num-100)*0.9*2;
//            System.out.printf("%.1f", finalNum);
//            System.out.print(df.format(finalNum));
            System.out.print(String.format("%.1f", finalNum));
        } else {
            return;
        }

    }

}

 

4、NumberFormat方案, 不足的是, 小数位为零的时候, 会省略小数点和后面的小数:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.NumberFormat;

public class Main4 {

    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        double num = Integer.parseInt(br.readLine());
        double finalNum = 0;
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(1);
        if(num > 100 && num <=300) {
            finalNum = (num-100)*0.9*2;
            System.out.println(nf.format(finalNum));
        } else {
            return;
        }

    }

}

 

posted @ 2018-12-06 20:32  HHZZHH  阅读(296)  评论(0编辑  收藏  举报