gpt4 book ai didi

java - 当给定特定范围时,程序不会猜测正确的数字

转载 作者:行者123 更新时间:2023-12-01 11:01:02 36 4
gpt4 key购买 nike

我正在编写一个程序,让计算机猜测你的号码。它必须猜测一个随机数。但它会猜测负数和超过 100 的数字,此外,它不会选择一个范围内的数字,就像如果人说计算机太高,程序会生成一个比原始猜测高的数字。

我使用了这里的随机范围方法:A

package compguse;
import java.util.*;

public class Compguse {


public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String a;
String b;
String c;
String ans;
String d;
int input =1;
System.out.println("do u have your number?");
a = scan.nextLine();
while (a.equalsIgnoreCase("yes"))
{
int ran = (int) Math.floor(Math.random()*100)+1;
System.out.println(" is " +ran +" your num?");
a = scan.nextLine();
while(a.equalsIgnoreCase("no"))
{
System.out.println("Was i too high or low?");
b = scan.nextLine();
if(b.equalsIgnoreCase("high"))
{
int ran1 = ran - (int)(Math.random()*100);
System.out.println("Is it " +ran1 +" humm?");
}
if(b.equalsIgnoreCase("low"))
{
int ran1 = ran + (int)(Math.random()*100);
System.out.println("Is it " +ran1 +" humm?");
}


}
}
}
}

最佳答案

您好,您的代码中有几个问题。

  1. 你的第二个 while 会一直循环,因为你从未更新过 a。

  2. 您应该在之前猜测的数字和最大值之间创建一个随机数或者在之前猜测的数字和较低的值之间。

  3. 您永远不会更新您的界限(最大值和最小值)。

要解决问题 1,您应该在两个 If block 之后添加

a = scan.nextLine();

要求解 2 和 3,请创建一个 max 和一个 min 变量,并将它们分别初始化为 100 和 0。然后在正确的 If 语句中更新它们,并根据之前猜测的数字和新的界限。例如,如果您猜得太高:

if(b.equalsIgnoreCase("high"))
{
max = ran;
ran = min + (int)(Math.random() * ((max - min) + 1))
System.out.println("Is it " +ran +" humm?");
}

关于java - 当给定特定范围时,程序不会猜测正确的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33321330/

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