public class Task06 {
public static void main(String[] args) {
// 声明部分
int x, target;
Scanner sc = new Scanner(System.in);
Random random = new Random();
// 产生猜测目标
target = random.nextInt(100);
// 输入猜测的整数
System.out.print("输入一个[1, 100]的整数:");
x = sc.nextInt();
while (x != target) {
// 判断是猜高了还是猜低了
if (x > target) {
System.out.println("朋友,你猜高了~继续猜吧");
} else {
System.out.println("朋友,你猜低了~继续猜吧");
}
// 继续输入猜测的整数
System.out.print("输入一个[1, 100]的整数:");
x = sc.nextInt();
}
System.out.println("恭喜你猜对了,游戏结束~");
}
}
结果如下
采用二分法来猜测,猜测次数最多不会超过l o g 2 100 ≈ 7 \mathrm{log}_2100\approx 7log
2100≈7
public class Task06_ {
public static void main(String[] args) {
// 声明部分
int target, x;
Scanner sc = new Scanner(System.in);
// 产生猜测目标
Random random = new Random();
target = random.nextInt(100);
while (true) {
// 用户输入猜测的数
System.out.print("输入一个[1, 100]的整数:");
x = sc.nextInt();
// 判断用户是否猜测正确
if (x > target) {
System.out.println("朋友,你猜高了~继续猜吧");
} else if (x < target){
System.out.println("朋友,你猜低了~继续猜吧");
} else {
break; // 猜中了,跳出循环
}
}
System.out.println("恭喜你猜对了,游戏结束!");
}
}