Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么Java中的除法只显示0?_Java_Casting_Operators - Fatal编程技术网

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

为什么Java中的除法只显示0?,java,casting,operators,Java,Casting,Operators,我在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 divis

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

(a/b)
您正在进行整数除法。您需要将类型转换为可以存储小数的其他数据类型,如
double

 double div = (double) a / b;

使用其他数据类型,然后使用int。int只是整数,没有小数。将a、b和div1更改为浮动或双精度