java使用abs函数_Java Math abs()用法及代码示例

Java 中的 Math.abs() 方法用于计算并返回参数的绝对值。对于不同类型的参数(如 float, double, int, long),该方法有不同的行为。例如,对于正零、负零、无穷大和NaN,它会返回相应的正值。当传入Integer.MIN_VALUE或Long.MIN_VALUE时,对于int和long类型,返回值仍然是相同的负值。" 132704793,19687569,C++ 实现 False Position 求根算法详解,"['算法', 'C++', '编程', '数值计算']

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

java.lang.Math.abs()返回给定参数的绝对值。

如果参数不为负,则返回参数。

如果参数为负,则返回参数的取反。

用法:

public static DataType abs(DataType a)

a:the argument whose absolute value is to be determined

返回: This method returns the absolute value of the argument.

如果参数为double或float类型:

如果参数为正零或负零,则结果为正零。

如果参数为无穷大,则结果为正无穷大。

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

如果参数为int或long类型:

如果参数等于Integer.MIN_VALUE或Long.MIN_VALUE的值,则最负

可表示的int或long值,结果是相同的值,为负。

// Java program to demonstrate working

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

import java.lang.Math;

class Gfg {

// driver code

public static void main(String args[])

{

float a = 123.0f;

float b = -34.2323f;

double c = -0.0;

double d = -999.3456;

int e = -123;

int f = -0;

long g = -12345678;

long h = 98765433;

// abs() method taking float type as input

System.out.println(Math.abs(a));

System.out.println(Math.abs(b));

// abs() method taking double type as input

System.out.println(Math.abs(1.0 / 0));

System.out.println(Math.abs(c));

System.out.println(Math.abs(d));

// abs() method taking int type as input

System.out.println(Math.abs(e));

System.out.println(Math.abs(f));

System.out.println(Math.abs(Integer.MIN_VALUE));

// abs() method taking long type as input

System.out.println(Math.abs(g));

System.out.println(Math.abs(h));

System.out.println(Math.abs(Long.MIN_VALUE));

}

}

输出:

123.0

34.2323

Infinity

0.0

999.3456

123

0

-2147483648

12345678

98765433

-9223372036854775808

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值