# need some Java help here

Discussion in 'OT Technology' started by Pro Street, Mar 9, 2005.

1. ### Pro StreetNew Member

Joined:
Oct 12, 2002
Messages:
70,787
0
Location:
Northern VA/Fucking Middle East
so I'm supposed to write a program, that does

pi = 4 - 4/3 + 4/5 - 4/7

and prints a table approximated by computing one or more terms ofthe series.

I'm limited to using do, while, for, and switch, and I suck at math so here's what I have so far.

Code:
```import java.util.Scanner;

public class pi
{
public static void main( String args[] )
{
Scanner input = new Scanner( System.in);

double piNumber = 0.0;
int denom = 1;
int term;
int count = 0;

System.out.print( "Enter the times to calculate the term in the series: ");
term = input.nextInt();

if ( term < 1 )
term = 1;

for ( term = 1; term >= count ; count++ )
{
if (count % 2 == 0 )
{
piNumber -= 4 / denom;
}
else
{
piNumber += 4 / denom;
}
System.out.printf( "%.2f\n", piNumber );
}

}
}```

2. ### Penguin ManProtect Your Digital Liberties

Joined:
Apr 27, 2002
Messages:
21,696
0
Location:
Edmonton, AB
I don't see you incrementing denom anywhere. I would have the for loop run from 0 to count / 2, with denom incrementing by two and changing sign each time (so denom would be 1, -3, 5, -7, 9...).

3. ### zabuniNew Member

Joined:
Jan 2, 2005
Messages:
64
0
I'd have the for loop go through and increment the divisor, and divide every time, and add that to pi. You should update denom every time in the above code, like so:

Code:
``` public class Pi
{
public static void main(String args[])
{
int terms=5, sign = 1;
double pi = 0;
for(int i = 1; i <= terms; i++)
{
int denom= 1+(i-1)*2;
pi += 4/(double)denom * sign;
sign *= -1;
}
}
}
```