Venusaur

Here's the problem:

Calculate the value of pi from the infinite series

pi = 4 - (4/3) + (4/5) -(4/7) + (4/9) - (4/11) + ...

Print a table that shows the value of pi approximated by computing one term of this series, by two terms, by three terms, and so on. How many terms of this series do you have to use before you first get 3.14 3.141 3.1415 3.14159 Here is the code I have so far:

Code Block

using System;

public class Pi

{

// Main method begins execution of C# application

public static void Main(string[] args)

{

double pi = 4;

for (int n = 1; n <= 100; n+=4)

{

pi = pi - (4 / (n + 2)) + (4 / (n + 4));

Console.WriteLine("{0,4}", pi);

}

} // end method Main

} // end class Pi

When I execute the code all I get is a line of 3s. Where is my math wrong



Re: Visual C# Language Please help me with C# code

Richard_Brundritt

Since n is an integer the calculation is done as an integer and then is stored in a double. This causes it to round off to 3. To fix this your code should look like this.

Code Block

using System;

public class Pi

{

// Main method begins execution of C# application

public static void Main(string[] args)

{

double pi = 4.0;

for (int n = 1; n <= 100; n+=4)

{

pi = pi - (4.0 / (n + 2.0)) + (4.0 / (n + 4.0));

Console.WriteLine("{0,4}", pi);

}

} // end method Main

} // end class Pi





Re: Visual C# Language Please help me with C# code

JohnWein

Since this is a homework problem, I won't supply code.

The math looks fine. Your coding is in need of help.

Here is what the steps would look like on paper:

PI = 4

PI - = 4/3

PI += 4/5

PI -= 4/7

PI += 4/9

. . .





Re: Visual C# Language Please help me with C# code

chatch15117

I've just started C#, but I have been doing some terminalIO stuff in java and one of the java apps calculates pi. the math should be the same.----

import java.util.Scanner;

public class PiCalculator{

public static void main(String[] args) {
// Declare Variables
Scanner reader = new Scanner(System.in);
double pi;
double x = 1;
double count = 0;
double no = 1;
double pi2 = 0;
double end;
double piCurrent;
//request input
System.out.print("Enter number of iterations: ");
end = reader.nextDouble();
//Calculations
while(count < end) {
pi = pi2 + (no / x);
x += 2;
no *= -1;
pi2 = pi;
piCurrent = pi2 * 4;
count ++;
}
pi = pi2 * 4;
//Display the value
System.out.println("The value of pi after " + end + " iterations is " + pi +
".");
}
}