我在Java程序中有以下方法:
public void Div(int a, int b){
//exception in order to check if the second argument is 0
try{
int div1 = (a / b);
double div = div1;
System.out.println("The division of the two numbers is: " + div);
}
catch(ArithmeticException e){
System.out.println("You can't divide a number by 0");
}
只有当分子大于分母(例如8/2(时,这才有效。如果分子小于分母,我得到的结果是0.0(例如2/8(。
我该怎么做才能让它正常工作?
这是因为整数除法。您可以将其中一个参数强制转换为double
,并将结果存储到double
变量中以解决此问题。
public class Main {
public static void main(String[] args) {
div(5, 10);
}
public static void div(int a, int b) {
try {
double div = (double) a / b;
System.out.println("The division of the two numbers is: " + div);
} catch (ArithmeticException e) {
System.out.println("You can't divide a number by 0");
}
}
}
输出:
The division of the two numbers is: 0.5
附带说明一下,您应该遵循Java命名约定,例如方法名称,根据Java命名约定Div
应该是div
。
(a/b)
您正在进行整数除法。您需要将类型转换为其他可以存储十进制的数据类型,如double
。
double div = (double) a / b;