229k views
5 votes
PI array

IN JAVA

Return an int[] that returns n many digets of PI. Eg: MakePi(3) -> [3, 1, 4] MakePi(6) -> [3, 1 ,4, 1, 5, 9]

User Luten
by
5.2k points

2 Answers

2 votes

Answer:

public static int[] MakePie(int n){

double pi = Math.PI;

int[] digits = new int[n];

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

digits[i] = (int) Math.floor(pi);

pi -= digits[i];

pi *= 10;

}

return digits;

}

Step-by-step explanation:

- Create a method called MakePie that takes the number of digits to be returned as a parameter

- Initialize the pi using Math class

- Initialize a new array digits that will hold the digits returned

- Inside the for loop, get the digits of the pi, starting from the beginning, and put the these into the digits array

- Return the digits array

User Shambolic
by
4.8k points
4 votes

Answer:

please find below explanation

Step-by-step explanation:

public class PITest {

// Define makePI method

public static int[] makePi(int n){

/*

* In PI value we have original value 3.141592653589793, so if we convert this

* into an string there will be 17 character in the string an indexing will be

* 0 to 16, so valid index are 0 to 16, we are checking here if a user pass index

* less then 0 or greater the 16 that will be an invalid index

* and we should process that index, and should return from the method

*/

if(n < 0 || n>16){

System.out.println("Inavlid index, Index must be between 0 to 16 ");

return null;

}

//decrare an array of size of the passed number i.e. n

int array[] = new int[n];

//get the value of PI from Math class

double pi = Math.PI;

//convert value of PI into an string and replace dot(.) from the string

String piString = String.valueOf(pi).replace(".","");

/*

* Iterate over the piString and get individual character from the string

* starting from zero and convert that character into int and keep(push) the converted value into the array

*/

for (int i = 0; i <piString.length(); i++) {

array[i]= Character.getNumericValue(piString.charAt(i));

}

// return the array

return array;

}

public static void main(String[] args) {

// to test makePI method call that method by passing an int value this method will return an array of integer

int arr[]= makePi(16);

// check if arr is not null

if(arr!=null){

// iterate over the array and print the values

for (int i = 0; i < arr.length; i++) {

System.out.print(arr[i]+" ");

}

}

}

}

User Monic
by
5.0k points