gpt4 book ai didi

java - 计算机猜测你的想法所需的猜测次数

转载 作者:行者123 更新时间:2023-12-01 16:51:14 26 4
gpt4 key购买 nike

好的,所以问题不一定是实际代码,因为它有效,而是逻辑。问题是计算机需要猜测多少次才能得出你的想法?在 1-100 之间,只要在 1-100 之间,无论是什么数字,它都会在 7 次尝试中猜出您的数字。下一个问题是1-50呢,我发现只需要尝试5次就可以猜出你的数字。

import java.util.Scanner;

public class ThinkofaNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Guess a number between 1 and 100");
System.out.println();
int input = 0;
//guess is equal to half the highest number
int guess = 50;
//low is equal to the lowest
int low = 1;
//high is equal to the highest number
int high = 101;
int tries = 1;

while (input != 2) {
System.out.println("Is your number " + guess + "?");
System.out.println("1: No, my number is lower");
System.out.println("2: Yes, that is my number");
System.out.println("3: No, my number is higher");
System.out.println();

input = in.nextInt();

if (input == 1) {
high = guess;
guess = low + (guess - low) / 2;
tries++;

} else if(input == 3) {
low = guess;
guess = guess + (high - guess) / 2;
tries++;
}

}


System.out.println("Your number is " + guess + "!");

if (tries == 1) {

System.out.println("It took 1 try to guess " + guess);

} else {


System.out.println("It took " + tries + " guesses to get " + guess);
}

}
}

问题是,如果数字在 1 到 400 之间,你认为最大猜测次数是多少?如果它在 1 到 800 之间怎么办? 1 到 1600 之间?我认为它试图让我找到一种模式或算法,但我没有看到它。大家觉得怎么样?

最佳答案

你所说的算法是二分查找算法。 https://en.wikipedia.org/wiki/Binary_search_algorithm

关于java - 计算机猜测你的想法所需的猜测次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39726286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com