Question

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;

    }
Was it helpful?

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;

}

OTHER TIPS

Edited to return array of int

var res = pi.ToString().Where(x => x != '.').Take(n).Select(x => (int)char.GetNumericValue(x)).ToArray();

Here is a solution that does not require a string conversion, since your ultimate goal was to return an int[].

 public int[] MakePie(int n){
    double pi = Math.PI;
    int[] result = new int[n];
    for (int i = 0; i < n; i++) {
        result[i] = (int) Math.Floor(pi);
        pi -= result[i];
        pi *= 10;
    }
    return result;
 }
private int[] getPiVal()
        {
            string pi = Math.PI + "";
            int[] piarray = new int[3];
            for (int i = 0; i < 3; i++)
            {
                piarray[i] = Convert.ToInt32(pi[i] + "");
            }
            return piarray;
        }

My strategy was to get each digit I wanted in the units position by multiplying PI by the relevant power of ten, and then getting the result of that number mod 10.

public int[] MakePi(int n)
{
    int[] result = new int[n]; 
    for (int i = 0; i < n; i++)
    {
        result[i] = (int)(Math.PI * Math.Pow(10, i)) % 10;
    }
    return result; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top