为什么Java中的除法只显示0?
我在Java程序中有以下方法:为什么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
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更改为浮动或双精度