2

I tried to do it but i'm getting 1.0 as answer every time i run it. I'm not being able to find out what's wrong please help me. Here are the codes:

import java.util.Scanner;
public class Number23 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n=0;
    float sum = 0,r = 0;

    System.out.print("Enter a number for n: ");
    n = input.nextInt();

    for(int x = 1; x <= n; x++)
    {
        r = (1/x);
        sum = sum + r;
    }

    System.out.print("The sum is "+sum);
 }

}
Manisha Singh Sanoo
  • 919
  • 1
  • 13
  • 42

2 Answers2

3

In order to produce a reciprocal that has a floating point value it is not enough to declare r a float: the expression you assign it needs to be float as well. You can do it by using the f suffix on the constant 1 which you divide by x:

r = (1f / x);

Without the suffix, your expression represents an integer division, which produces an integer result, and drops the fraction. In your case, the only time that you get a value other than zero is when x is equal to 1.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
-1
class reciprocal
{
    public static void main ( int n)
    {
        float i,a,s=0;
        for(i=1;i<=n;i++)
        {
            a= 1/i;
            s+=a;
        }
        System.out.print( "sum is "+s);
    }
}
Prudhvi
  • 2,276
  • 7
  • 34
  • 54