0

Here is my code, Eclipse always return integer value of results, even if h is double. Please help me to fix this.

public static void main(String[] args) {
    double h=0.0;

    for(int i=1;i<=1000;i++) {
        h=h+ 1/i;           
    }
    System.out.println("Harmonic sum "+h);
    System.out.println("Harmonic sum "+String.format("%.4f", h));

Result:

Harmonic sum 1.0
Harmonic sum 1,0000
Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
Rocky
  • 19
  • 5

1 Answers1

-1

You need to cast the result of your division into double

Try this out:

h=h+ (double)1/i;

I hope this is what you were looking for.

Safeer Ansari
  • 742
  • 4
  • 12
  • Why are you answering an obvious duplicate question? – Hovercraft Full Of Eels Nov 23 '17 at 17:05
  • And if you must do so, please make sure that the quality of your answer surpasses most of the duplicate answers to be found. – Hovercraft Full Of Eels Nov 23 '17 at 17:06
  • Casting the result wouldn't help, but the code you wrote doesn't do what you say anyway. It actually casts one _operand_, the `1`, to `double`, and then JLS 5.6.2 promotes the other operand `i` to `double` and the division is done in `double` which works -- but was more accurately and quickly stated by ElliotFrisch. – dave_thompson_085 Nov 23 '17 at 18:46