3.4 jmu-java- random number - pi value calculation using the Monte Carlo method (10 minutes)

import java.util.Scanner;
java.util.Random import;
public class Main {

        public static void main(String[] args) {
             Scanner sc = new Scanner(System.in);
            long seed=sc.nextLong();
            int n=sc.nextInt();     
             Random  random= new Random(seed);

            double  x,y=0;
           
            long k=0,i=0;
            for(i=0;i<n;i++){
                int s;
                if (i<1/n) {s=1;}
                else {s=-1;}
                x = random.nextDouble () * s; // generates a random number
                y= random.nextDouble()*s;
              
                if(x*x+y*y<1) k++;
               
            }
            double pi=4*(double)k/(double)i;
            System.out.println(pi);
            sc.close();
        }
    }
This code can be run on the PTA was an error in eclipse. Because I do not know how to generate a random number between -1 and 1.

Guess you like

Origin www.cnblogs.com/zlshy/p/11532389.html