gpt4 book ai didi

java - 基本的 Java 数组和 For 循环

转载 作者:行者123 更新时间:2023-11-29 04:16:35 25 4
gpt4 key购买 nike

我正在上 Java 类(class)并一遍又一遍地阅读相同的解释,我只是想确保我正确理解它。

他们提供的类(class)中的示例是一个掷骰子游戏,他们想查看每个数字的掷骰频率。

我不确定的代码片段是这样的:

for(int roll = 1; roll < 1000; roll++){
++freq[1+rand.nextInt(6)];
}

我理解这部分:1+rand.nextInt(6)

但我不明白这部分:++freq 以及它如何统计结果

我的理解是(以我掷出 4 的例子为例):

for(int roll = 1; roll < 1000; roll++){
++freq[4];
//all indexes in freq are == 0 to start
//freq[4] is index 4 in the array. It was 0 but is now == to 1
//freq[0], freq[1], freq[2], freq[3], freq[5], and freq[6] are all still == to 0
}

for(int roll = 1; roll < 1000; roll++){
++freq[6];
//freq[6] is index 6 in the array. It was 0 but is now == to 1
//freq[0], freq[1], freq[2], freq[3], and freq[5] are all still == to 0
//freq[4] and freq[6] are both == to 1
}

这是正确的吗?

最佳答案

int[] freq = new int[7];

for(int roll = 1; roll < 1000; roll++){
++freq[1+rand.nextInt(6)];
}

在上面的代码中,rand.nextInt(6) 返回一个从 0 到 5 的值,用于访问数组 freq 的相关整数值

++freq部分将访问的整数值加1。

例子: 如果 rand.nextInt(6) 返回 2

freq[1 + 2] = freq[1 + 2] + 1;

但是,从 1 + rand.nextInt(6) 开始,永远不会产生 0。因此,freq 数组的第一个元素应该被忽略。

freq[n] 将为您提供第 n 面孔的频率。

关于java - 基本的 Java 数组和 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52018642/

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