java 中subtract的用法,Java Math subtractExact(int a , int b)用法及代码示例

java.lang.Math.subtractExact()是java中的内置数学函数,该函数返回参数的差值。不需要。

用法:

public static int subtractExact(int a, int b)

参数:

a:the first value

b:the second value to be subtracted from the first

返回:

This method returns the difference of the arguments .

Exception:

It throws ArithmeticException - if the result overflows an int

例:展示java.lang.Math.subtractExact()方法的用法。

// Java program to demonstrate working

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

import java.lang.Math;

class Gfg1 {

// driver code

public static void main(String args[])

{

int a = 300;

int b = 200;

System.out.println(Math.subtractExact(a, b));

}

}

输出:

100

// Java program to demonstrate working

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

import java.lang.Math;

class Gfg2 {

// driver code

public static void main(String args[])

{

int x = Integer.MIN_VALUE;

int y = 10;

System.out.println(Math.subtractExact(x, y));

}

}

输出:

Runtime Error:

Exception in thread "main" java.lang.ArithmeticException:integer overflow

at java.lang.Math.subtractExact(Math.java:829)

at Gfg2.main(File.java:13)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当我们将`typedef std::function<int(int, int)> MathFunction`作为参数时,可以将函数对象作为参数传递给函数,并在函数内部使用该函数对象进行操作。下面是一个使用`MathFunction`作为参数的例子: ```cpp #include <iostream> #include <functional> typedef std::function<int(int, int)> MathFunction; int calculate(MathFunction mathFunc, int a, int b) { return mathFunc(a, b); } int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int multiply(int a, int b) { return a * b; } int main() { int a = 5; int b = 3; MathFunction mathFunc; mathFunc = add; std::cout << "Addition result: " << calculate(mathFunc, a, b) << std::endl; mathFunc = subtract; std::cout << "Subtraction result: " << calculate(mathFunc, a, b) << std::endl; mathFunc = multiply; std::cout << "Multiplication result: " << calculate(mathFunc, a, b) << std::endl; return 0; } ``` 在这个例子,我们定义了一个函数`calculate`,它接受一个`MathFunction`类型的参数`mathFunc`,以及两个`int`类型的参数`a`和`b`。在`calculate`函数内部,我们通过调用`mathFunc(a, b)`来执行传入的函数对象,并返回结果。 在`main`函数,我们声明了一个名为`mathFunc`的`MathFunction`对象,并依次将`add`、`subtract`和`multiply`赋值给它。然后,我们通过调用`calculate`函数,并传递`mathFunc`作为参数,以及`a`和`b`作为操作数,来计算不同的数学操作的结果。 这个例子展示了如何将`typedef std::function<int(int, int)> MathFunction`作为参数传递给函数,并在函数内部使用该函数对象进行操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值