Pergunta

Here is an easy one that I am having trouble with. The problem requires me to write a method called fractionSum which accepts an integer parameter and returns a double of the sum of the first n terms.

for instance, if the parameter is 5, the program would add all the fractions of (1+(1/2)+(1/3)+(1/4)+(1/5)). In other words, it's a form of the Riemann sum.

For some reason, the for loop does not accumulate the sum.

Here's the code:

public class Exercise01 {

public static final int UPPER_LIMIT = 5;

public static void main(String[] args) {
    System.out.print(fractionSum(UPPER_LIMIT));
}

public static double fractionSum(int n) {

    if (n<1) {
        throw new IllegalArgumentException("Out of range.");
    }

    double total = 1;

    for (int i = 2; i <= n; i++) {
        total += (1/i);
    }

    return total;
}

}
Foi útil?

Solução

you need to type cast to double

try this way

public class Exercise01 {

public static final int UPPER_LIMIT = 5;

public static void main(String[] args) {
    System.out.print(fractionSum(UPPER_LIMIT));
}

public static double fractionSum(int n) {

    if (n<1) {
        throw new IllegalArgumentException("Out of range.");
    }

    double total = 1;

    for (int i = 2; i <= n; i++) {
        total += (1/(double)i);
    }

    return total;
}

}

Outras dicas

The operation

(1/i)

is working on integers and hence will generate the result in terms of int. Update it to:

(1.0/i)

to get the fractional result and not the int result.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top