when I declare the counter (i variable) as an integer, I get the wrong answer:
int i = 1;
double d = 0;
for (; i<= 10; i++){
d = d + (1/i);
}
System.out.println("The value using for loop: \n" + d);
Output: The value using for loop: 1.0
but when I declare the counter as a double I get the answer right:
double i = 1;
double d = 0;
for (; i<= 100; i++){
d = d + (1/i);
}
System.out.println("The value using for loop: \n" + d);
Output: The value using for loop: 5.187377517639621
I declared the final sum as a double because I don't want to lost any numbers at the end. But what is the point of declaring the integer as a double to get the right answer? I believe the counter (i) should be incremented by one each time, so it should be integer.