+ 1

How is it possible ?..

double sum=0; for(int i=1;i<=10;i++) sum+=1/i; System.out.print(sum);

13th Apr 2018, 6:44 AM
Motwkel Mohammed
Motwkel Mohammed - avatar
4 Antworten
+ 8
The result is 1.0 because you divide one integer (1) by another integer (i), so the decimal places are cut off and AFTER the cutting the result is casted to double. Replace 1/i with 1.0/i and the result will be correct.
13th Apr 2018, 7:03 AM
Tashi N
Tashi N - avatar
+ 2
because the i. is an int and 1 is an int too so the decimal part won't get saved change ur code to. sum =1.0 /i ;
13th Apr 2018, 7:01 AM
Farshaad Heydari
Farshaad Heydari - avatar
+ 1
t y :)
13th Apr 2018, 7:14 AM
Motwkel Mohammed
Motwkel Mohammed - avatar
+ 1
You can either change 1 to 1.0, or you can cast it by adding (double) before 1. The answer is 2.9289.. , if you want to round it to 2.93 use the following: sum+= Math.round((1.0/i)*100.0)/100.0; Good luck! CA
13th Apr 2018, 3:06 PM
Cris Ahmad
Cris Ahmad - avatar