Help with Fraction with java

Asked

Viewed 299 times

0

I want to make the following algorithm:

300/15 + 350/14 - 400/13 + 450/12 - .....

That is, when the denominator is odd it adds up to the next result, if it is even it decreases.

Here’s my code, but it’s giving me a different result than the calculators:

// one class needs to have a main() method
public class HelloWorld {
    // arguments are passed using the text field below this editor
    public static void main(String[] args) {
        double numerador = 300.0;
        double resultado = 0.0;
        for (int i = 15; i > 0; i--) {
            if (i % 2 == 0) {
                resultado = resultado - (numerador / i);
                System.out.println("s " + numerador);
                System.out.println(i);
                System.out.println(resultado);
            } else {
                resultado = (numerador / i) + resultado;
                System.out.println("d " + numerador);
                System.out.println(i);
                System.out.println(resultado);
            }
            numerador = numerador + 50;
        }

        System.out.println(resultado);
    }
}
  • I found no mistake in yours program. I even tested the sequence on Wolfram to see if the result was the same. But it has something strange in its sequence: if when the denominator is odd it adds (+) and when it is even subtracts (-), then why is the second term 340/14 positive? The signals should alternate...

  • In the question you put the expression 300/15 + 350/14 - 400/13 + 450/12..., but the code is doing 300/15 - 350/14 + 400/13 - 450/12 ... - maybe that’s the reason for the confusion.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.