我哪里做错了?为什么我的方法返回无穷大?

huangapple go评论87阅读模式
英文:

Where did I messed up? Why is my method returning Infinity?

问题

public class Vehicle {
    int passengers;
    int fuelcap;
    int mph;
    Vehicle(int p, int f, int m) {
         passengers = p;
         fuelcap = f;
         mph = m;
    }
    double fuelNeeded(int miles) {
        return (double) miles / mph;
    }
}

public class STUFF {
    public static void main(String[] args) {
        Vehicle minivan = new Vehicle(7, 16, 21);
        Vehicle sportscar = new Vehicle(2, 14, 12);
        double gallons;
        int dist = 252;
        gallons = minivan.fuelNeeded(dist);
        System.out.println(gallons);
        gallons = sportscar.fuelNeeded(dist);
        System.out.println(gallons);
    }
}
Output:
12.0
21.0

If you have been getting "Infinity" as output, the issue might have been due to incorrect assignments in the Vehicle constructor. Make sure to assign the parameters to the corresponding instance variables, as shown in the corrected code above. This should fix the problem and provide you with the correct output.

英文:
public class Vehicle {
    int passengers;
    int fuelcap;
    int mph;
    Vehicle(int p, int f, int m) {
         p = passengers;
         f = fuelcap;
         m = mph;
    }
    double fuelNeeded (int miles) {
        return (double) miles/mph;
    }
}
public class STUFF {
    public static void main(String[] args) {
        Vehicle minivan = new Vehicle(7, 16, 21);
        Vehicle sportscar = new Vehicle(2, 14, 12);
        double gallons;
        int dist = 252;
        gallons = minivan.fuelNeeded(dist);
        System.out.println(gallons);
        gallons = sportscar.fuelNeeded(dist);
        System.out.println(gallons);

    }
}
Output:
Infinity
Infinity

I have been stuck on this problem for quite sometimes now, I'm not sure where I messed up but the method keeps outputing the result as Infinity, it would be much helpful if you guys can give me some insights to where and how the code was wrong. Thank you so much!!

答案1

得分: 1

你正在将局部变量(pfm)赋予全局变量的值,但你应该反过来进行:

Vehicle(int p, int f, int m) {
     passengers = p;
     fuelcap = f;
     mph = m;
}

因为这个原因,在fuelNeeded函数中你正在进行除以0的操作,导致结果为Infinity

英文:

You are assigning the local variables (p, f, m) the values of your global variables, but you should be doing it the other way around:

Vehicle(int p, int f, int m) {
     passengers = p;
     fuelcap = f;
     mph = m;
}

Because of this, you are dividing by 0 in fuelNeeded, which results in Infinity.

huangapple
  • 本文由 发表于 2020年4月5日 17:24:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/61040479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定