如何修复 android 中被零除的问题

how to fix divide by zero in android

它不起作用!!

我用过不同的方法破案都没有效果

谁能帮帮我?

................................................ ...................................

           case '/':

                    pp = Double.parseDouble(text.getText().toString());


                    if (sss == '/') {
                        if (Double.parseDouble(text.getText().toString()) == 0.0 ||Integer.parseInt(text.getText().toString()) == 0) {

                            text.setText("");
                            text2.setText("");
                            Toast.makeText(getBaseContext(), "Cannot divide by zero", Toast.LENGTH_SHORT).show();

                        } else if (pp != 0 || pp != 0.0) {

                            vis = tt / pp;

                            temp = (int) vis;
                            if (vis == temp) {

                                text.setText(Integer.toString(temp));
                            } else {

                                text.setText(Double.toString(vis));
                            }

                            vis = 0;
                            ash = 0;
                            break;

                        }
                    }

浮点数除以零不是错误,结果只是无穷大。查看除法后的结果:

case '/':

  pp = Double.parseDouble(text.getText().toString());


  if (sss == '/') {

    vis = tt / pp;

    if (Double.isInfinite(vis)) {
      text.setText("");
      text2.setText("");
      Toast.makeText(getBaseContext(), "Cannot divide by zero", Toast.LENGTH_SHORT).show();
    } else {

      temp = (int) vis;
      if (vis == temp) {
        text.setText(Integer.toString(temp));
      } else {
        text.setText(Double.toString(vis));
      }

      vis = 0;
      ash = 0;
      break;

    }
  }

不要让您的代码如此复杂。仅使用 Double 变量,因为在除法中你需要回答某些 precision.Also double 类型变量的除法运算存在问题,因为它们不会抛出 Arithmetic exception.E.g.:

0/0 - generates ArithmeticException
1.0/0 - generates output NaN(infinite)

接缝"pp"是double类型。 所以写一些这样的东西:

double tt=Double.parseDouble(textView1.getText().toString().trim());
double pp=Double.parseDouble(textView2.getText().toString().trim());

if(pp!=0){
    x=tt/pp;
    System.out.println(" res :"+x);
}else{
    //you logic if pp is 0
}

如果分母为零,则通过使用简单检查(分母==0)避免计算,或者保持原样,以便当分母为零时显示结果 NaN(无限)。