嵌套 for 循环和变量的放置
Nested for loops and the placement of variables
我目前正在尝试解决一个问题,我试图在三角数组中找到最小的三角项和。 (我目前使用的数组是一个3x3的三角数组)
colAmt =1;
int tempCol = rows;
int tempSum=0;
rows = 3;
for(int t=0;t<rows;t++)
{
for(int col = 0; col<colAmt; col++)
{
tempCol=0;
tempSum =0;
for(int m=t;m<rows;m++)
{
System.out.println(m+", "+tempCol);
tempSum = tempSum + sumTriangle[m][tempCol];
tempCol++;
if(tempSum<triSum)
{
triSum = tempSum;
}
}
}
colAmt++;
}
当我执行程序时,程序打印出:
(0, 0)
(1, 1)
(2, 2)
(1, 0)
(2, 1)
(1, 0)
(2, 1)
(2, 0)
(2, 0)
(2, 0)
应该打印的时间:
(0, 0)
(1, 1)
(2, 2)
(1, 0)
(2, 1)
(1, 1)
(2, 2)
(2, 0)
(2, 1)
(2, 2)
我很确定我处理 tempCol 变量的方式有问题,但我不确定如何解决它。
任何帮助表示赞赏。谢谢!
你可以通过替换
来得到你想要的数字
tempCol=0;
和
tempCol=col;
我目前正在尝试解决一个问题,我试图在三角数组中找到最小的三角项和。 (我目前使用的数组是一个3x3的三角数组)
colAmt =1;
int tempCol = rows;
int tempSum=0;
rows = 3;
for(int t=0;t<rows;t++)
{
for(int col = 0; col<colAmt; col++)
{
tempCol=0;
tempSum =0;
for(int m=t;m<rows;m++)
{
System.out.println(m+", "+tempCol);
tempSum = tempSum + sumTriangle[m][tempCol];
tempCol++;
if(tempSum<triSum)
{
triSum = tempSum;
}
}
}
colAmt++;
}
当我执行程序时,程序打印出:
(0, 0)
(1, 1)
(2, 2)
(1, 0)
(2, 1)
(1, 0)
(2, 1)
(2, 0)
(2, 0)
(2, 0)
应该打印的时间:
(0, 0)
(1, 1)
(2, 2)
(1, 0)
(2, 1)
(1, 1)
(2, 2)
(2, 0)
(2, 1)
(2, 2)
我很确定我处理 tempCol 变量的方式有问题,但我不确定如何解决它。 任何帮助表示赞赏。谢谢!
你可以通过替换
来得到你想要的数字tempCol=0;
和
tempCol=col;