猜数游戏(单次版)

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("恭喜你猜对了,游戏结束!");
    }
}
在这里插入图片描述

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值