0

write java programme, using DO and WHILE to approximate 22/7 (pi)= 4-4/3+4/5-4/7+4/9-4/11+4/13..

4
Contributors
4
Replies
8
Views
4 Years
Discussion Span
Last Post by subramanya.vl
0

I'm a first year Java student and
I need some help with a practice problem

Write java programme, using DO and WHILE to approximate 22/7 (pi)= 4-4/3+4/5-4/7+4/9-4/11+4/13..

Here is what i've tried so far:

 public static void main(String[] args){
    double sum = 0;        
    int count = 1;
        do {
            double numToAdd = 1.0 / ((i * 2) - 1);
        sum += numToAdd;
            count++;
        } while (sum += numToAdd;);
    }
}

Thank You

0

you have put double variable "numToAdd" inside the do-while loop and
you are accessing it in while condition like this

} while (sum += numToAdd;);// this will not compile 

This is incorrect , since variable "numToAdd" is not visible outside the flower brackets {} of do-while loop.
Hence declare the variable "numToAdd" outside the do-while loop.

Also while condition checks for boolen result

while(sum += numToAdd) // this will not compile , hence modify the condition.

while condition checks for a boolean result. Hence this code will not compile.

I also observed
(pi)= 4-4/3+4/5-4/7+4/9-4/11+4/13..

But in your code you are only doing addition , where are you doing subtraction.

double numToAdd = 1.0 / ((i * 2) - 1);//this will not compile since variable i is not declared in your code

Edited by subramanya.vl

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.