public class DivideExample {
// 定义一个 divide 函数,用于两个整数的除法运算
public static double divide(int numerator, int denominator) {
// 检查分母是否为零,避免除以零的错误
if (denominator == 0) {
throw new ArithmeticException("分母不能为零");
}
// 返回除法结果,使用 double 类型以保留小数部分
return (double) numerator / denominator;
}
public static void main(String[] args) {
// 示例调用 divide 函数
try {
double result = divide(10, 2);
System.out.println("10 / 2 = " + result);
// 测试除以零的情况
result = divide(10, 0);
System.out.println("10 / 0 = " + result);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
divide
函数接收两个整数参数:numerator
(分子)和 denominator
(分母),并返回它们的商。ArithmeticException
异常,以避免程序崩溃。main
方法中,我们展示了如何调用 divide
函数,并处理了除以零的情况。上一篇:java redis分布式锁实现
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站