-1

So I'm trying to do math on ints stored in an array of ints.

    float day1Hours = (day1[3]-day1[2]) / 2;

for this specific problem, day1[3] = 19 and day1[2] is 10. So, it should be doing 19-10 = 9, and then dividing that by 2 to make 4.5. But, the output that I am getting is 4. I've also tried storing day1Hours as a double but that made no difference. How would I make this be able to do the math correctly and get those decimal values that I need?

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
Sydney
  • 3
  • 2
  • correction: it would be 19-10. Sorry, typo. – Sydney Jan 26 '18 at 20:18
  • The result of `day1[3]-day1[2]` is an `int`. `2` is an int. When diving an int by another int, you can never get a number with decimal places (double/float). Divide by `2.0`. – nbokmans Jan 26 '18 at 20:19
  • Java truncates decimal values on integer division. You either need to have your array values stored as floats or cast the integers to floats. – C Henry Jan 26 '18 at 20:19

3 Answers3

2

The problem is that you are doing integer division and then converting to a float. Try

float day1Hours = (day1[3]-day1[2]) / 2.0f;

Using a float literal in the denominator will cause the division to be done in floating point, and you won't get integer truncation. (As an alternative to using a float literal, you could cast the numerator or denominator to a float, but that seems somewhat baroque to me. It would be more suitable if both the numerator and denominator were int variables.)

The reason that just changing the type of day1Hours doesn't affect the problem is that the entire right side is evaluated first using the declared data type of day1 and then converted to whatever type is on the left of the assignment.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0
float day1Hours = (float)(20-9) / 2; //5.5
George Z.
  • 6,643
  • 4
  • 27
  • 47
  • Please provide details rather than a code-only answer - [From Review](https://stackoverflow.com/review/low-quality-posts/18637828) – K.Dᴀᴠɪs Jan 26 '18 at 21:13
0

Problem is that on the right side of equation the numbers are integers and when dividing 2 integers the decimal places are truncated (integer division rounds towards zero) 4.5 -> 4.0.

Try changing 2 -> 2f so the 2 would be considered a float instead of an integer.

KKaar
  • 225
  • 1
  • 2
  • 10