gpt4 book ai didi

java - 如何快速、轻松地在Java中初始化大量变量?

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:26 25 4
gpt4 key购买 nike

所以我有一个非常基本的编码问题,我今年才开始学习,我有一个代码作业,应该是

flip a fair coin n times and count how many heads it gets. The program will do m experiments and then print out the results as a (vertical) histogram. The program will first ask the user to input the number of experiments to perform (m) and the number of coin flips in each experiment (n). n can be at most 79. The output will be a histogram made up of spaces and asterisks (*), with n+1 columns (for the number of heads which can go from 0 to n)

我已经完成了直方图的代码,但我遇到的问题是如何将头部数量存储为它自己的变量。例如,如果它抛硬币 80 次,其中 40 次是正面,我希望它为 40 次抛硬币创建一个 int,然后向其中添加 1。我只是不知道如何在不写出 int one = 0; 的情况下初始化 80 个变量。整数二 = 0,整数三 = 0;直到时间结束,然后编写 80 个 if 语句,直到找到正确的整数加一。有没有一种简单的方法可以做到这一点,或者我应该采取不同的方法?这是代码,请温柔一点,实际上只需一个月左右的时间就可以进入一个非常基本的 java 类

 for(m=m; m>0; m--) { //runs m number of experiments of n coinflips, keeping track of total heads
n = o; // when N gets set to 0 through the while loop, o resets it back to it's original so it can loop again
while(n>0) {
n--;
if(random.nextBoolean()) {
heads++;
total++;
/** here is where I want the number of heads saved to a
variable, so that way later I can run a loop to put as many *'s as I need in the histogram later */

最佳答案

只需使用一个数组进行 80(或 n)次实验:

I don't understand, this would just count how many heads/tails there are right? This doesn't save them (ie it flipped 5 heads 6 times, 4 heads 3 times, 3 heads twice, ect) unless I'm misunderstanding

如果您要存储磁头数 m 次(其中 m 为 < 80),您可以:

1) 在生成结果时打印直方图(不需要数组)OR

2) 将 80 个结果存储在数组中

<小时/>

1 的示例(无数组):

for(int x=0; x<experiments; x++){
int heads = 0;
for(int y=0; y<flips; y++){
if(rnd.nextInt(2) == 0) //assume 0 is head
heads ++;
}
//print histogram
for(int y=0; y<heads; y++)
System.out.print("*");
System.out.println();
}

2 的示例(带数组):

int[] expr = new int[80];    //store results for 80 experiments
for(int x=0; x<expriments; x++)
for(int y=0; y<flips; y++)
if(rnd.nextInt(2) == 0)
expr[x] ++;

关于java - 如何快速、轻松地在Java中初始化大量变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40664979/

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