Java 中的 double 除法

Haider Ali 2023年10月12日
Java 中的 double 除法

在这里,在本指南中,我们将清除 Java 中双除法中出现的混淆。要完全理解这一点,我们需要熟悉 Java 中的数据类型。看看下面的规则。

  1. 两个整数之间的任何算术运算都会给出一个整数作为输出。
  2. integer 和 double 之间的任何算术运算都会给出 double 值。

你可以说数据类型 double 的优先级高于整数,因此任何涉及 double 和 integer 的运算都会给出 double 值。

Java 中的整数 double 除法

看看下面的代码。

import java.util.*;
import javax.naming.spi.DirStateFactory.Result;
public class Main {
  public static void main(String args[]) {
    int x = 8;
    int y = 30;
    double z = y / x;
    System.out.println(z);
  }
}

你认为这个程序会给出什么输出?3.0 或 3.75。它将是 3.0,因为我们只是将两个整数相除,给出一个整数作为输出,在本例中为 3。我们将此输出存储在 double z 中,由于数据类型为 double,它变成了 3.0。

因此,我们需要应用强制转换以获得以下代码可以执行的精确输出。

import java.util.*;
import javax.naming.spi.DirStateFactory.Result;
public class Main {
  public static void main(String args[]) {
    int x = 8;
    int y = 30;
    double z = (double) y / x;
    System.out.println(z);
  }
}

输出:

3.75

在这里,(double) 用于 Java 中的类型转换。因此,yx 都变成了 double。除法后,输出将以 double 数据类型存储 z,这也是一个 double。因此,输出将为 3.75。

作者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相关文章 - Java Math