+ 2

C#: How does one stop a loop after certain digits have been reached for a double?

So, I am trying to approximate pi up to 10 digits. I am using do-while loops to do so. I need the program to stop when the approximation has reached 3.14159265, then output the iteration number. However, as you know, with approximation, the number will NEVER be exactly 3.141592650000....., the 0..... part will always have some further decimal-numeric value. I tried converting the pi-approximation variable to a string in another holder. The string did not have enough digits. Main Question So, is there a way to stop a loop when a decimal up to ten "correct" digits past the decimal? Let me know if this question is unclear. Here is what I have so far..... It does not work however. Obviously it is within the normal namespace codes, name space, and class. //following code should create sequence (4/(2*n+1)) nE[0,r] private static int PiA(int r) { double pi = 0.0; // pi holder double i = 0.0; string pi1; do { double t = ((4 / ((2 * i) + 1)) * (Math.Pow(-1, i))); pi += t; i++; r++; } while (pi1[4] !=1 && pi1[5] !=5 && pi1[6] !=9 && pi1[7] !=2 && pi1[8] != 6 && pi1[9] != 5); return r; } static void Main(string[] args) { Console.WriteLine(PiA(200000)); } }

12th May 2018, 6:40 PM
Paul Blum
Paul Blum - avatar
1 Answer
+ 3
I would like to help but before that please provide a Minimal, Complete, and Verifiable code @ Code Playground so we can help you to take a look on the code. 😉
12th May 2018, 11:23 PM
Zephyr Koo
Zephyr Koo - avatar