数组
package com.day12_05_02;
import java.util.Scanner;
public class Text1 {
public static void main(String[] args) {
* 统计随机数的改进 //int[] f=new int[6];相当于创建一个数组可以存放六个int类型的数,并且初始值为0; int[]
* f={0,0,0,0,0,0,}; for(int i=1;i<=60000;i++){ int face
* =(int)(Math.random()*6+1); f[face-1]++; } for(int
* i=1;i<=f.length;i++){ System.out.println(i +"出现了"+f[i-1]+"次" ); }
*/
/*
* //斐波拉切数 int[] f=new int[30]; f[0]=f[1]=1; for(int
* i=2;i<f.length;i++){ f[i]=f[i-1]+f[i-2]; } //for-each 循环(只读循环)
* //for(int x:f){ //System.out.println(x); //} for(int
* i=0;i<f.length;i++){ System.out.println(f[i]);
*
* } System.out.println((float)f[f.length-2]/f[f.length-1]);
*/
// 统计学生成绩
String[] name = { "关羽", "张飞", "赵云", "马超", "黄忠" };
double[] scores = new double[name.length];
double total = 0;
double max = scores[0];
double min = scores[0];
Scanner input = new Scanner(System.in);
for (int i = 0; i < name.length; i++) {
System.out.println("请输入" + name[i] + "个学生的成绩");
scores[i] = input.nextDouble();
}
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
for (int i = 1; i < scores.length; i++) {
if (max < scores[i]) {
max = scores[i];
} else if (min > scores[i]) {
min = scores[i];
}
}
System.out.println("最高分:" + max + " 最低分:" + min);
System.out.println("平均分:" + total / scores.length);
input.close();
}
}
案例-约瑟夫问题
- 练习:有三十个人,其中有十五个基督教徒,一起坐船,结果船坏了,要把十五个人扔到海里
才能得救,大家决定围城一圈,从某个人开始报数,从1-9,报到9的扔到海里,继续报数,依次
类推,知道把所有的人扔到海里,结果十五个基督教徒都没被扔进海里,问这些人最初是怎么
站位的,哪些位置是基督教徒?(约瑟夫问题)
package com.day12_05_02;
public class Text2 {
public static void main(String[] args) {
boolean[] peoples = new boolean[30];//默认都是false
for (int i = 0; i < peoples.length; i++) {
peoples[i] = true;
}
int counter = 0;// 记录杀死了多少人
int inDex = 0;// 操作数组的下标
int number = 0;// 报数的值
while (counter <= 15) {
if (peoples[inDex]) {
number++;
if (number == 9) {
peoples[inDex] = false;
counter++;
number = 0;
}
}
inDex++;
if (inDex == peoples.length) {
inDex = 0;
}
}
for (boolean isChrist : peoples) {
System.out.print(isChrist ? "基" : "非");
}
}
}
案例-捕鱼问题
- 5个人打鱼,分成五份,丢掉多余的一条,取走属于自己的一份,
五个人都用相同的办法分鱼,问至少有多少条鱼
package com.day12_05_01;
public class HomeWork2 {
public static void main(String[] args) {
for (int i = 1;; i++) {
int total = i;
boolean isEnough = true;
for (int j = 1; j <= 5; j++) {
if ((total - 1) % 5 == 0) {
total = (total - 1) / 5 * 4;
} else {
isEnough = false;
break;
}
}
if (isEnough) {
System.out.println(i);
break;
}
}
}
}
冒泡排序
package com.day12_05_02;
public class Text3 {
public static void main(String[] args) {
int[] x={23,67,12,99,58,77,88,4,45,81};
xuanzhe(x);
for(int a:x){
System.out.print(a+" ");
}
}
public static void maopao(int[] x) {
boolean swapped =true;
for(int i=1;swapped&&i<x.length;i++){
swapped=false;
for(int j=0;j<x.length-i;j++){//后面的元素已经排好序了,不用在进行两两比较
if(x[j]>x[j+1]){
int temp=x[j];
x[j]=x[j+1];
x[j+1]=temp;
swapped=true;
}
}
}
}
}