0

The problem with my code is that when I input 0, the result is 0.0 but whenever I enter anything more than zero, (like 1,2,3,4,5,6, 998...anything) the result is always 1.0 in each case. Is my logic incorrect inside the iteration?

My code:

    /*/  Write a y program that will calculate the value of y if the expression 
of y is as follows (n is the input):

        y = 1/1 + 2/3 + 3/5 + 4/7 + ....... + n/(2n-1)     /*/

import static java.lang.System.*;
import java.util.*;

class Practice_Problems04_JavaPrograms_Task04{
    public static void main(String[] args){
        Scanner orcho = new Scanner(in);
        out.println("Please enter the value of n: ");
        int n = orcho.nextInt();
        double y = 0;

        for(int count = 1; count <= n; count++){
            y += (count / ((2 * count) - 1));
        }
        out.println("The summation is, y = " + y);
        orcho.close();
    }
}

3 Answers3

4

count / ((2 * count) - 1) is integer division, you need float number division, change to count / ((2 * count) - 1.)

When two integers made a division operation, then integer operation is performed, a / b is equal to the math operation a/b with fraction part removed.

1 / 2   -> 0.5  ->  0
3 / 2   -> 1.5  ->  1
-3 / 2  -> -1.5 -> -1
-3 / -2 -> 1.5  -> 1

As a matter of fact, (a / b) * b + (a % b) is always equal to a.

To perform a float number division, one of a and b need to be a float number, you can use both implicit and explicit conversion. Like a * 1. / b or (double)a / b

You can check java 8 specs for multiplicative operators and type conversion.

The type of a multiplicative expression is the promoted type of its operands. If the promoted type is int or long, then integer arithmetic is performed. If the promoted type is float or double, then floating-point arithmetic is performed. 15.17

delta
  • 3,643
  • 13
  • 21
0

You are dividing ints together, which always produce an int. You should use doubles in order to get your result:

for(double count = 1; count <= n; count++){
    y += (count / ((2 * count) - 1));
}
T. Claverie
  • 8,107
  • 1
  • 10
  • 24
0

Alternatively to what T & delta have mentioned you could try explicit type casting in the division so that the division actually returns a value of type correctness.

References: https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

Thanks,

-Abe.

Abraham
  • 220
  • 2
  • 15