2

Possible Duplicate:
Java loss of precision

ok so for a program that I'm writing I have called "Flight" I created a method that calculates the amount of fuel to be used during the flight. I am getting 2 errors on my code though that says "possible loss of precision found: double required: int" can anyone help me find out why I'm getting this error?

here is my code for that method:

public double calculateFuel(){
    if (numofmiles<1000){
      numofmiles = numofmiles*2;
    }
    else if (numofmiles>1000 && numofmiles<3000){
      numofmiles = numofmiles*1.75;
    }
    else if (numofmiles>3000){
      numofmiles = numofmiles*1.5;
    }
    //basing off of that a plane goes 30 miles on 1 gallon
    double fuel = numofmiles/30;

    return fuel;
  }
Community
  • 1
  • 1
Andrew
  • 151
  • 2
  • 7
  • 14
  • numofmiles is declared at the beginning of the class as an int. In the tester I use File reader to get the numofmiles and other info about the object from a file called input.txt. – Andrew May 07 '12 at 22:11
  • When you assign a double to a float, an long to an int, a float to an int, etc, without an explicit cast you will get the warning. In the above case, if `numofMiles` is a long or int you'll get the warning on the middle two multiplies because you're assigning a double to an int. – Hot Licks May 07 '12 at 22:11
  • 1
    Well, there you go. `numofmiles * 1.5` might not be an exact integer, and it's complaining that you'll need to round. – Louis Wasserman May 07 '12 at 22:11
  • 2
    ohhhh wow I feel pretty stupid ahaha – Andrew May 07 '12 at 22:12

3 Answers3

2

numofmiles needs to be declared as a double, not an integer.

apnorton
  • 2,430
  • 1
  • 19
  • 34
0

declare numOfMiles as a double. A loss of precision means that you are losing information of the given value. if numOfMiles is an integer value of 1035 it would be multiplied by 1.75. this would result in a value of 1811.25 which is not an integer value. truncating the value to satisfy the variable declaration results in a loss of precision.

Itchy Nekotorych
  • 882
  • 3
  • 10
  • 24
0

You should use the double primitive type or BigDecimal for arbitrary precision.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207