Search code examples
c#arrayspi

Return an int array length n containing first n digits of pi? (c#)


Per the subject line I am trying to return an int array length n containing the first n digits of pi.

So MakePi(3) --> {3, 1, 4}

I know I need to get pi and it gets stored as a double. I need to convert the double to a char so that I can search through the array to find each char, n in length. Then convert it back to an int array.

I am having issues on where to go from here. I know there is a loop but I can't get my brain to figure out exactly what I need to do. Thanks!

public int[] MakePie(int n)
      {
        double pi = Math.PI;
        char newPi = Convert.ToChar(pi);
        char[] newArray = new char[n];
        newArray[0] = newPi;
        int numbers = Convert.ToInt32(pi);

        for (int i = 0; i < n; i++)
        {


        }
        return newArray;

    }

Solution

  • try this: it will also get rid of the decimal.

    public static int[] MakePie(int n)
      {
        double pi = Math.PI;
        var str = pi.ToString().Remove(1, 1);
        var chararray = str.ToCharArray();
        var numbers = new int[n];
    
        for (int i = 0; i < n; i++)
        {
    
            numbers[i] = int.Parse(chararray[i].ToString());
        }
        return numbers;
    
    }