java 题目 四舍五入

描述

写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于 0.5 ,向上取整;小于 0.5 ,则向下取整。
 
数据范围:保证输入的数字在 32 位浮点数范围内

输入描述:

输入一个正浮点数值

输出描述:

输出该数值的近似整数值

示例1

输入:
5.5
输出:
6
说明:
0.5>=0.5,所以5.5需要向上取整为6   

示例2

输入:
2.499
输出:
2
说明:
0.499<0.5,2.499向下取整为2   

方法一
 1 import java.io.*;
 2 import java.util.*;
 3 
 4 public class Main{
 5     public static void main(String[] args) throws IOException {
 6         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 7         
 8         String input;
 9         if((input = br.readLine()) != null) {
10             float f =Float.parseFloat(input);
11             System.out.println(Math.round(f));
12         }
13     }
14 }

 

方法二

 1 import java.io.*;
 2 public class Main {
 3         public static void main(String[] args) throws IOException{
 4             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 5             String str = br.readLine();
 6             int index = str.indexOf(".");
 7             int a = Integer.parseInt(str.substring(0,index));
 8             int b = Integer.parseInt(str.substring(index+1,index+2));
 9             if(b >= 5){
10                 System.out.println(a+1);
11             }else{
12                 System.out.println(a);
13             }
14              
15         }
16 }

 

方法三

import java.util.*;
import java.io.*;
public class Main{
    public static void main(String[] args) throws Exception{
        BufferedReader  in = new BufferedReader(new InputStreamReader(System.in));
        String line = in.readLine();
        in.close();
         
        String[] arr = line.split("\\.");
        int base = Integer.parseInt(arr[0]);
        char a =arr[1].toCharArray()[0];
        if(a >= '5'){
            base = base + 1;
        }
        System.out.print(base);
         
    }
}

 

posted @ 2022-02-13 21:29  海漠  阅读(76)  评论(0编辑  收藏  举报