|
-
September 27th, 2011, 04:49 PM
#1
Formatting
As a lab assignment for uni, We were given a task to write a simple program that used an infinite series to calculate pi (4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11.....)
This is what I came up with so far and it works fine!
Code:
public class Picalc
{
public static void main(String[]args)
{
int runs=20;
double total=0, series;
boolean positive=true;
System.out.println("Pi Number of Terms\n___________________________________________");
for (double x=0; x<runs; x++)
{
series = 1/(2*x+1);
if (positive)
total+= series;
else
total-= series;
positive = !positive;
System.out.println(+total*4.0+"\t\t"+(x+1));
}
}
}
<- link to console output
My problem and questions are regarding the output. Basically because of the default printing of doubles It's printing the majority with 23 decimals, is there anyway to force it to say 6 places when printing so that my column with the number of terms is lined up nicely.
Last year we programmed mainly in C, there was an easy way to do the above with the print function but as I'm still unfamiliar with Java's syntax I'm not sure if there's a simple solution to what I'm trying to do.
Is there a better way to do what I'm doing overall?
Because it's a college assignment at the start of the year I plan to keep it relatively simple but it'd be nice to trim off the rough edges.
Thanks in advance for any help!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|