我的一项家庭作业是编写一个带有 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/