【问题标题】:Why does division in Java displayonly 0? [duplicate]为什么Java中的除法只显示0? [复制]
【发布时间】:2020-04-16 07:13:24
【问题描述】:

我在一个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)的结果。

我该怎么做才能让它发挥作用?

【问题讨论】:

  • 使用其他数据类型然后 int。 int 只是整数,没有小数。将 a、b 和 div1 更改为 float 或 double

标签: java casting operators


【解决方案1】:

这是因为整数除法。您可以将参数之一转换为 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

【讨论】:

    【解决方案2】:

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

     double div = (double) a / b;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多