*程序4-10
蒙特卡罗方法估算π:边长为2的正方形,其内切圆的面积为π;那么随机往该正方形的范围里点一个点,该点落于圆范围内的概率为π/4。
随机丢N个点,N越大,落于圆内的点数/N就越接近π/4.
算法中对“落于圆内”的判定方法:距离原点<=1则为真。具体仅判断第一象限内的点.
- import javax.swing.JOptionPane;
- public class C0401 {
- public static void main(String[] args){
- double x,y,d;
-
- String s1=JOptionPane.showInputDialog("请输入你要测试的次数");
- int totalTimes=Integer.parseInt(s1);
- int countTimes=0,i;
- for(i=1;i<=totalTimes;i++){
- x=Math.random();
- y=Math.random();
- d=x*x+y*y;
- if(d<=1) countTimes++;
- }
- double Pi=(double)countTimes/totalTimes*4;
- JOptionPane.showMessageDialog(null,"本次估算PI="+Pi+".");
- }
- }
*程序4-14
在5行中显示从2开始的前50个素数,每行包含10个数。
- public class C0402 {
- public static void main(String[] args){
- int number=1,x,counter=0;
- for(number=2;counter<=50;number++){
- for(x=2;x<=number/2;x++){
- if(number%x==0)
- break;
- }
- if(x==(number/2+1)){
- counter++;
- System.out.printf("%4d ",number);
- if(counter%10==0)
- System.out.printf("\n");
- if(counter>=50)
- break;
- }
- }
- }
-
- }
*程序4-15
使用确认对话框控制循环:从2开始判断是否为素数,提示输入整数,判断;提示是否继续输入判断。
- import javax.swing.JOptionPane;
- public class C0403 {
- public static void main(String[] args){
- int number,a;
- String s1;
- int option=JOptionPane.YES_OPTION;
- while(option==JOptionPane.YES_OPTION){
- s1=JOptionPane.showInputDialog("请输入一个整数");
- number=Integer.parseInt(s1);
- if(number==1||number==0)
- JOptionPane.showMessageDialog(null,"输入值"+number+"不是一个素数");
- else{
- for(a=2;a<=number/2;a++){
- if(number%a==0)
- break;
- }
- if(a>=(number/2+1))
- JOptionPane.showMessageDialog(null,"输入值"+number+"是一个素数");
- else
- JOptionPane.showMessageDialog(null,"输入值"+number+"不是一个素数");
- }
- option=JOptionPane.showConfirmDialog(null,"是否继续输入值以判断素数?");
-
- }
- }
-
- }
|