输出是 "NaN"

Output is "NaN"

所以,我开发了一个 class,假设供另一个 class 使用。我开发的class如下:

public class Car
{
private double milesPerGallon;
private double gas;

//Constructs a car with a given fuel efficiency
public Car(double milesPerGallon)
{
    gas = 0.0;
}

//Increases the amount of gas in the gas tank
public void addGas(double amount)
{
    gas = gas + amount;
}

//Decreases the amount of gas in the gas tank (due to driving and therefore consuming gas)
public void drive(double distance)
{
    gas = gas - (distance / milesPerGallon);
}

//Calculates range, the number of miles the car can travel until the gas tank is empty
public double range()
{
    double range;
    range = gas * milesPerGallon;
    return range;
}
}

假设使用我开发的class的class是:

public class CarTester
{
/**
 * main() method
 */
public static void main(String[] args)
{
    Car honda = new Car(30.0);      // 30 miles per gallon

    honda.addGas(9.0);              // add 9 more gallons
    honda.drive(210.0);             // drive 210 miles

    // print range remaining
    System.out.println("Honda range remaining: " + honda.range());

    Car toyota = new Car(26.0);      // 26 miles per gallon

    toyota.addGas(4.5);              // add 4.5 more gallons
    toyota.drive(150.0);             // drive 150 miles

    // print range remaining
    System.out.println("Toyota range remaining: " + toyota.range());
}
}

两个 classes 都编译成功,但是当程序是 运行 我得到输出 "NaN," 代表 "Not a Number." 我查了一下,据说它发生了当有一个数学过程试图除以零或类似的东西时。我不是,我再说一遍,不是在寻找答案,而是在正确的方向上轻推我可能会犯错误的地方将不胜感激(我确信这是一个非常小而愚蠢的错误)。谢谢!

在构造函数中保存您的 milesPerGallon 变量:

public Car(double milesPerGallon)
{
   this.milesPerGallon = milesPerGallon;
   gas = 0.0;
}

您没有在 Car 构造函数中初始化 milesPerGallon。所以它以 0.0 作为默认值。当一个数字除以 0.0 你会得到 NaN.

milesPerGallon需要初始化为构造函数参数

构造函数:

public Car(double milesPerGallon)
{
    this.milesPerGallon = milesPerGallon;
    gas = 0.0;
}

milesPerGallon 稍后使用但从未初始化。

您似乎没有初始化 milesPerGallon。您在构造函数中接受的变量与您在 class 顶部初始化的私有变量不同。通常人们喜欢使用 public car(aMilesPerGallon) 之类的东西来确保他们知道其中的区别。或者正如我在打字时发布的答案所说,this.milesPerGallon 引用 class 顶部的变量。

您没有在构造函数中设置 milesPerGallon,因此它被初始化为 0.0。你在某处除以那个变量吗?