gpt4 book ai didi

java - 增强的 for 循环和 float 组

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

我的一项家庭作业是编写一个带有 float 的小增强 for 循环。根据我的理解,我理解这种整数数组循环样式的基础:

for (int i = 0; i < some.number; i++) 

相当于

for (int i : array_example)

如果这是准确的,这应该如何处理充满 float 的数组?我认为增量运算符 (i++) 只能用于整数。只是想寻求一些说明。

谢谢。

编辑:这是我正在做的事情的一个例子,以及 Eclipse 不喜欢的事情。这可能增加了我的困惑:

public class java_array 
{
public static void main(String[] args)
{
float[] values = {1/2,1/3,5/3};
float total = 0;
for (float i : values)
{
values[i] = i; //Getting an error here "can't convert from float to int.
}
for (float i : values)
{
System.out.println(values[i]); //Getting an error here "can't convert from float to int.
}
}
}

一切都被声明为float。为什么 IDE 会这样说?

最佳答案

增强的 for 循环,返回数组中的,而不是索引

在整数情况下,if myArray = [2,4,6,8];

for (int i : myArray)
// returns 2,4,6,8, NOT 0,1,2,3

在传统的循环中,你有一个额外的步骤

for (int idx = 0; idx<myArray.length; i++) {
// idx will be 0,1,2,3
int value = myArray[i]; <<< in many cases this is an extra step
// value will be 2,4,6,8
}

现在,如果您出于某种原因需要索引和值,则需要老式循环。

因此,对于 floatArray 上的老式循环,您需要一个 int 作为索引,一个 float 作为值。如果 floatArray = [2.2, 4.4, 6.6, 8.8]

   for (int idx = 0; idx<floatArray .length; i++) {
// idx will be 0,1,2,3
float value = floatArray [i];
// value will be 2.2, 4.4, 6.6, 8.8
}

有了增强的for循环,你只需要一个float

  for (float value : floatArray ) {
// value will be 2.2, 4.4, 6.6, 8.8

关于java - 增强的 for 循环和 float 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20225735/

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