Java写题解的第1天:取近似值

三种常见思路,见代码注释

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        float f = Float.parseFloat(br.readLine());
        br.close();        
        System.out.println(multiply2ThenMinus(f));
    }

    // 方法一:乘2强制转int,再减去本身强制转int 
    public static int multiply2ThenMinus(float f) {
        return (int)(f*2) - (int)f;
    }

    // 方法二:加0.5强制转换int
    public static int plusHalf(float f) {
        return (int)(f+0.5);
    }

    // 方法三:乘10强制转换int,再判断个位数和5的大小
    public static int judge(float f) {
        int n = (int)(f * 10);
        return (n % 10 < 5)? n / 10 : n / 10 + 1;
    }
}