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);
}
}
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
.