java的round函数怎么用_Java Math round()用法及代码示例

Java的Math.round()函数用于将浮点数四舍五入为最接近的整数,返回值为long类型。当参数为NaN时返回0,参数为负无穷大或小于或等于Integer.MIN_VALUE时返回Integer.MIN_VALUE,参数为正无穷大或大于或等于Integer.MAX_VALUE时返回Integer.MAX_VALUE。示例代码中展示了如何使用此方法并打印结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java.lang.Math.round()是内置数学函数,它返回最接近参数的long。通过将1/2相加,将结果四舍五入为整数,再加上1/2后取结果的下限,并将结果强制转换为long类型。

如果参数为NaN,则结果为0。

如果参数为负无穷大或任何小于或等于Integer.MIN_VALUE的值,则结果等于Integer.MIN_VALUE的值。

如果参数为正无穷大或任何大于或等于Integer.MAX_VALUE的值,则结果等于Integer.MAX_VALUE的值。

用法:

public static int round(float val)

Parameter:

val - floating-point value to be rounded to an integer.

返回值:

该方法返回四舍五入到最接近的int值的参数值。

例:演示java.lang.Math.round()函数的工作

// Java program to demonstrate working

// of java.lang.Math.round() method

import java.lang.Math;

class Gfg {

// driver code

public static void main(String args[])

{

// float numbers

float x = 4567.9874f;

// find the closest int for these floats

System.out.println(Math.round(x));

float y = -3421.134f;

// find the closest int for these floats

System.out.println(Math.round(y));

double positiveInfinity = Double.POSITIVE_INFINITY;

// returns the Integer.MAX_VALUE value when

System.out.println(Math.round(positiveInfinity));

}

}

输出:

4568

-3421

9223372036854775807

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值