-1

I am trying to write a Java program that finds the sum of the following series using an input for the value of n:

formula

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!

learning123
  • 103
  • 4

2 Answers2

1

The problem lies here:

sum = sum + ((double)(i/(i+1)));

You cast only the rounded integer. You can think of it like this:

int a = i / (i + 1);
double b = (double) a; // = a.0

Just move the cast to the next parenthesis:

sum = sum + ( (double) i / (i+1) );
Daniel
  • 669
  • 3
  • 19
  • 2
    You mean `int a = i / (i+1)` . Due the precedence rules in the grammar (and common to nearly all languages other than APL and Forth) `(i / i + 1)` is the same as `(i/i) + 1` which for nonzero `i` is the same as `(1+1)` or `2`. – dave_thompson_085 May 22 '21 at 20:09
1

This happens because you are dividing using integers and then casting the value to double. You should cast one of the integers before dividing them by each other, like: ((double)i)/(i + 1). When you are dividing using integers, the JVM always returns an integer by rounding down the value, so you have to cast one of them before dividing.

learning123
  • 103
  • 4
Programmer
  • 531
  • 2
  • 10