gpt4 book ai didi

Java:随机类建议

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:10:51 24 4
gpt4 key购买 nike

所以我应该创建一个程序,生成 100 个介于 1 和 1000 之间的随机整数,然后告诉返回偶数和奇数的整数的数量。到目前为止,我已经把那部分记下来了。但是,我无法弄清楚第二部分。我需要做同样的事情 10 次,然后我需要将所有这些加在一起得到总数。

import java.util.Random;

public class EvenOrOdd
{
public static void main(String[] args)
{
int even = 0, odd = 0;
int iteration = 0;

while (iteration<10)
{
for(int i = 0; i<100;i++)
{
int number2 = random.nextInt(1000) + 1;
if ((number2 % 2) == 0)
{
even++;
}
else if ((number2 % 2) == 1)
{
odd++;
}

}
System.out.println("Iteration " + " Evens " + " Odds");
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
}
System.out.println("\nEvens: " + even + "\nOdds: " + odd);
}
}

我试过取出

System.out.println("Iteration " + " Evens " + " Odds");

并将它放在 while 循环之上,然后删除除其中一个之外的所有内容

    iteration++;
System.out.println(iteration + " " + even + " " + odd);

但是当我这样做时,我的偶数和赔率在每次迭代中几乎翻了一番。

所以再重复一遍我想做的事:我想做每一个

    iteration++;
System.out.println(iteration + " " + even + " " + odd);

显示新的偶数和奇数,而不是同一个。然后,因为我也不知道该怎么做,所以我想把十个偶数和十个赔率加起来。感谢您的帮助!

最佳答案

您几乎就在那里,主要问题是您在 while 循环内将迭代递增 10 次,因此它会立即退出 while 循环。我刚刚删除了所有这些增量,它起作用了!

此外,在 while 循环外有一个偶数和奇数的总计数器,然后在 while 循环中的每次迭代后将总数相加,如下所示:

public class EvenOrOdd {

public static void main(String[] args) {

Random random = new Random();
int evenTotal = 0, oddTotal = 0;
int iteration = 0;

System.out.println("Iteration " + " Evens " + " Odds");

while (iteration < 10) {
int even = 0, odd = 0;
for (int i = 0; i < 100; i++) {
int number2 = random.nextInt(1000) + 1;
if ((number2 % 2) == 0)
even++;
else if ((number2 % 2) == 1)
odd++;

}
iteration++;
System.out.println(iteration + " " + even + " " + odd);
evenTotal += even;
oddTotal += odd;
}
System.out.println("\nEvens: " + evenTotal + "\nOdds: " + oddTotal);
}

}

关于Java:随机类建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654083/

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