import java.util.*; import java.lang.*; import java.io.*; class Ideone { public static void main(String args[]) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(r.readLine()); ff g = new ff(); System.out.println(g.sum(3)); } } class ff { double sum(int b) { double sum = 0; for (int i = 0; i < b; i++) sum += (i + 1) / (i + 2); return sum; } } 

Given a positive integer n , it is necessary to calculate the sum of n members of the sequence 1/2 + 3/4 + 5/6 + 7/8 + ...

Why is it considered wrong?

    1 answer 1

    To make the division not integer, you can, for example, add 1.0 * to the beginning of the expression.

    Also, either the summation should involve 2 * i :

     sum += 1.0 * (2 * i + 1) / (2 * i + 2); 

    Or i should go up to 2 * n with step 2 :

     for (int i = 0; i < 2 * n; i += 2) { sum += 1.0 * (i + 1) / (i + 2); } 

    An entire example:

     public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); double sum = 0; for (int i = 0; i < 2 * n; i += 2) { sum += 1.0 * (i + 1) / (i + 2); } System.out.println(sum); } 

    And using Java 8 and transforming the formula, it might look like this:

     double sum = IntStream.range(1, n + 1).mapToDouble(i -> 1 - 0.5 / i).sum();