为什么 Java 中的除法只显示 0?

Why does division in Java displayonly 0?

我在 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 naming conventions 例如根据 Java 命名约定,方法名称 Div 应该是 div

(a/b) 你在做整数除法。您需要转换为其他可以存储小数的数据类型,例如 double.

 double div = (double) a / b;