I am trying to write a Java program that finds the sum of the following series using an input for the value of n:
The code I have written is as follows:
package sum_of_series1;
import java.util.Scanner;
public class Sum_of_series1
{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
int n, i;
double sum;
sum = 1;
System.out.println("Enter the value of n:");
n = sc.nextInt();
i = 0;
while (i<n)
{
i++;
sum = sum + ((double)(i/(i+1)));
}
System.out.println("The sum of the series is " + sum);
}
}
However, the output is the following for every input of n:
The sum of the series is 1.0
Clearly, this is incorrect (for say n = 4). After some inspection, I realised that ((double)(i/(i+1)))
is being calculated as 0.0
every time. Why is it not, for example, calculating 2/3
as 0.6666666666666666
and how can I fix this problem?
Strangely, however, when I write System.out.println((double) 2/3)
, the output is 0.6666666666666666
. I am rather new to programming and extremely confused. Any help would be much appreciated!