取近似值

https://www.nowcoder.com/practice/3ab09737afb645cc82c35d56a5ce802a?tpId=37&tqId=21230&tPage=1&rp=&ru=%2Fta%2Fhuawei&qru=%2Fta%2Fhuawei%2Fquestion-ranking

 

一、题目描述

写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于5,向上取整;小于5,则向下取整。

 

二、代码实现

1、利用类型之间的强转

题目已经明确输入只有正浮点数,不用考虑负浮点数的情况。不过,不过出现负数,则也是可以先减去0.5,再强转;或者先强转,再乘以10之后判断除以10的余数是否大于等于5,如果是则将强转后的结果减1。

import java.util.Scanner;
public class Main {
    
    public static void main2(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextDouble()) {
            double input = sc.nextDouble();
            
            int result = (int)input;
            if ((input*10 % 10) >= 5) {    //或者  if (input - result >= 0.5)
                result++;
            }
            
            System.out.println(result);
        }
    }
    
    public static void main1(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNextDouble()) {
            double input = sc.nextDouble();
            
            input = input + 0.5;
            int result = (int)input;
            
            System.out.println(result);
        }
    }
}

2、直接使用Math.round()

import java.util.Scanner;
public class Main {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNextDouble()) {
            double input = sc.nextDouble();
            
            if (input < 0) {
                //题目已经明确输入的只有正浮点数,所以不要这个判断也行
                sc.close();
                return;
            }
            
            System.out.println(Math.round(input));
        }
    }

}

3、考虑大数据

BigDecimal类的四舍五入方法可以查看此链接:

https://blog.csdn.net/ahwr24/article/details/7048724

import java.util.Scanner;
import java.math.BigDecimal;
public class Main {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNextDouble()) {
            double input = sc.nextDouble();
            
            BigDecimal result = new BigDecimal(input).setScale(0, BigDecimal.ROUND_HALF_UP);
            
            System.out.println(result);
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值