gpt4 book ai didi

java - 我编写了一个在循环中随机生成 0 和 1 的程序。如何使程序在连续生成十个 0 时停止循环?

转载 作者:行者123 更新时间:2023-12-01 06:28:53 24 4
gpt4 key购买 nike

这是我迄今为止拥有的鳕鱼:

public class Laboratoire05E {
public static void main(String[] args) {

int number = 0;
int counter = 0;

do {
bin = (int) (Math.random()*2);
System.out.print(bin);
counter++;

if(counter>=80) {
System.out.print("\n");
counter = counter-80;
}
} while (bin < 2);
}

}

控制台输出如下:

01000111000011101011010011011000000100100110100101011011010100111011111110110111001011000010011000100011001010011011100110001101101110101000100111110001011100110000001011110101111010010010010000010100111100011000110101001100000111010000001110100001001011100110100110010011100110001110100111111110111101111000010100001110110110011100011011111101110101111111101001101000001000010111000111000110010001010100111111101100110100001011101011101011110000110101000110000110101111101000111100110010110101100010000101001111011111

并且这种情况会无限期地持续下去。

最佳答案

请记住,您的循环可能会在 (.5^10) = 0.0977 % 的情况下连续找到 10 个“0”。如果您增加该金额,您可能需要在 counter 超过生成数字数量的某个阈值时进行额外检查。

int zeroCount = 0
do {
bin = (int) (Math.random()*2);
System.out.print(bin);
counter++;

// Check for 10 in row:
if(bin == 0) {
zeroCount ++;
} else {
zeroCount = 0;
}
if(zeroCount == 10) {
break; // Exit loop
}

if(counter>=80) {
System.out.print("\n");
counter = counter-80;
}
} while (bin < 2);

关于java - 我编写了一个在循环中随机生成 0 和 1 的程序。如何使程序在连续生成十个 0 时停止循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12865421/

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