gpt4 book ai didi

java - 如何在循环中修复我的随机数?

转载 作者:行者123 更新时间:2023-12-03 23:33:41 26 4
gpt4 key购买 nike

我需要做的是制作一个数字生成器,它在生成 10 时停止并显示在达到 10 之前有多少次尝试。为此,我还必须仅使用 while 循环。这是我的代码:

public static int RandomOccurrence()
{
int randNumber = (int)(Math.random()*20 + 1);
int count = 0;

while(randNumber != 11){
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}

这是函数调用:

int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");

System.out.println();
System.out.println();

但是当我运行代码时,它会无限打印“生成的数字是 2”。

最佳答案

这是您的代码的固定版本,主要涉及将获取随机数的行移到 while 循环中:

public static int RandomOccurrence()
{
int randNumber = 0;
int count = 0;

while(randNumber != 10){//I changed the 11 to 10 because you said you wanted to stop at 10
randNumber = (int)(Math.random()*20 + 1);//added
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}

System.out.println(RandomOccurrence());

示例结果:

The number generated is 1
The number generated is 4
The number generated is 20
The number generated is 19
The number generated is 10
5

关于java - 如何在循环中修复我的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64671931/

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