3个题目,建议你分开问,不然没人给你答的。
第一个的代码:
public class Test {
//判断x、y是否是边界点
public static boolean isBandge(int x,int y){
if(x == 1 || x == 9 || y == 1 || y== 9)
return true;
else
return false;
}
public static void main(String[] args){
int row = 5, col = 5; // 棋子的初始位置
int rd = 0; //随机数
double step = 0,all = 0;
for(int i=0;i<10000;i++){
//重置参数
step = 0;
row = 5;
col = 5;
//开始移动,通过生成0、1、2、3的随机数来表示上 、右、下、左移动
while(!(isBandge(row,col))){
step++; //步数+1
rd = (int)(Math.random()*4); //生成[0,4)的随机数
if(rd == 0){ //向上移动
col--;
}else if(rd == 1){ //向右移动
row++;
}else if(rd == 2) { //向下移动
col++;
}else if(rd == 3){ //向左移动
row--;
}
} //while end
all += step; //累计步数
} //for end
all /= 10000; //求平均值
System.out.println("平均值:"+all);
}
}
运行结果(因为移动是随机的,所以最后得到的平均数不会完全一致):
第二题代码:
public class Test {
//判断x是否是Fibonacci数列中的数字
public static boolean isFibNmb(double x,double arr[]){
for(int i=0;i<arr.length;i++){
if(arr[i] == x)
return true;
}
return false;
}
public static void main(String[] args){
double arr[] = new double[75]; //保存Fibonacci数列的前75项
//得到前75项Fibonacci数列
arr[0] = 1;
arr[1] = 1;
for(int i=2;i<75;i++)
arr[i] = arr[i-1]+arr[i-2];
//遍历所有可能
for(int i=0;i<75;i++){
for(int j=i+1;j<75;j++){
double x = arr[i]*arr[i] + arr[j]*arr[j];
//判断x是否在arr中
if(isFibNmb(x,arr)){
System.out.printf("%.0f,%.0f,%.0f\n",x,arr[i],arr[j]);
}
}
}
}// main end
}
运行结果: