我在跟踪数组练习时得到的结果与编译器不同 [英] Im getting a different result than the compiler when tracing array excercise
本文介绍了我在跟踪数组练习时得到的结果与编译器不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我跟踪代码获得答案的1,3,5,7时,编译器会打印1,3,6,10
我无法理解这种情况的发生,谁能解释
when i trace the code im getting 1,3,5,7 for the answer but the compiler prints 1,3,6,10
im having trouble understanding how this happens could anyone explain
int [] a= new int[5]; // create array
for (int i =1; i<=4; i++)
{
a[i]=a[i-1]+i;
System.out.print(a[i]+" ");
}
推荐答案
当我trace代码
您调试它.调试时,您可以一行计算出几种操作:
when itracethe code
You debug it. While debugging you figure several operations in one line:
for (int i =1; i<=4; i++)
{
a[i]=a[i-1]+i;
System.out.print(a[i]+" ");
}
应该是
should be
for (int i =1; i<=4; i++)
{
int iNumber = a[i-1]; // get number of previous field
iNumber += i; // add counter
a[i]=iNumber; // place result
System.out.print(a[i]+" ");
}
这样,您可以计算每个步骤并查看输出是否为"1 3 6 10".
This way you can figure every step and see that the output if this is "1 3 6 10".
这篇关于我在跟踪数组练习时得到的结果与编译器不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文