2

Why is that this simple operation in a for loop such as this one returns 0.0?

totaalPunten += (moduleScore * (double)(moduleStudiePunten/totaalStudiepunten));

Where totaalPunten is a double initialized outside of the for-loop as 0, moduleScore (i.e. 12.0) and moduleStudiePunten (i.e. 6) are the following:

double moduleScore = entry.getValue().getScore();
int moduleStudiePunten = entry.getValue().getAantalStudiePunten();

entry is a HashMap entry. totaalStudiepunten is an int which is always 30. I'm not even sure if I should be casting (moduleStudiePunten/totaalStudiepunten) to double. Either way, I'm stumped as to how this isn't working. Does it have something to do with the way incrementing works? It's quite likely I have a made a huge mistake in Java considering I'm starting to get familiar with it coming from C# (student).

Alexis C.
  • 91,686
  • 21
  • 171
  • 177

1 Answers1

0

Change the following line from:

totaalPunten += (moduleScore * (double)(moduleStudiePunten/totaalStudiepunten));

To:

totaalPunten += (moduleScore * (moduleStudiePunten / (double) totaalStudiepunten));

Output when i run comes as 2.4000000000000004

SMA
  • 36,381
  • 8
  • 49
  • 73
  • Yea, just found it out. I thought casting the entire division to double would work but apparently I have to cast either the denominator or the numenator, glad to know it, thanks. – Pieter-Jan Vandenbussche Feb 14 '15 at 18:15