当我在第二个for循环中进行计算时,它不能正确计算。我将只计算数组中的最后一个数字,而不计算其他两个。if块计算正确。我要做的就是把每一个都拿走[row][col]值并除以temp3并显示在数组中。请建议。提前谢谢你。Avi
package tester;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner inFile = new Scanner(new FileReader("one.txt"));
float [][] glassdata = new float[3][4];
loadArray(glassdata, inFile);
displayArray(glassdata);
System.out.println("n***************n");
normalizingVector(glassdata);
}
public static void loadArray(float [][] g, Scanner inFile)
{
for(int row = 0; row < g.length; row++)
{
for(int col = 0; col < g[row].length; col++)
{
g[row][col] = inFile.nextFloat();
}
}
}
public static void displayArray(float [][] g)
{
for(int row = 0; row < g.length; row++)
{
for(int col = 1; col < g[row].length; col++)
{
System.out.print(g[row][col] + " ");
}
System.out.println();
}
}
public static void normalizingVector(float [][] g)
{
float temp1 = 0;
float temp2 = 0;
float temp3 = 0;
float temp4 = 0;
for (int row = 0; row < g.length; row++)
{
for(int col = 1; col < g[row].length; col++)
{
if(col < g[row].length)
{
temp1 = (float) Math.pow(g[row][col], 2);
temp2 = temp2 + temp1;
}
temp3 = (float) Math.sqrt(temp2);
temp4 = (g[row][col]) / temp3;
//System.out.print((g[row][col] / temp3) + " ");
System.out.print(temp4 + " ");
}
//System.out.print(temp3);
System.out.println();
temp1 = 0;
temp2 = 0;
temp3 = 0;
temp4 = 0;
}
}
}
你的normalizingVector
方法有一些冗余,基本上什么也不做。唯一被赋值的值是temp1
, temp2
, temp3
和temp4
,它们是本地的,在for循环的每次迭代时都被设置为0。
我稍微重写了一下你的代码:它现在只使用一个临时变量,在每次外层循环迭代开始时设置为0(你也可以在最后这样做,但在我看来,如果你在开始时这样做,你的代码更容易阅读)。注意,temp1
初始值为0,并且每次迭代都以访问的数组元素的平方值递增。形式为t += a
的语句是t = t + a
的缩写。我用它来简化代码。
public static void normalizingVector(float [][] g)
{
float temp1;
for (int row = 0; row < g.length; row++)
{
temp1 = 0;
//col should start from 0, unless you intended that
for(int col = 0; col < g[row].length; col++)
temp1 += (float) Math.pow(g[row][col], 2);
temp1 = (float) Math.sqrt(temp1);
for(int col = 0; col < g[row].length; col++)
g[row][col] = g[row][col] / Math.sqrt(temp1);
}}
您需要添加第二个内部for循环,因为在规范化vector时,您希望vector的每个元素都除以它的长度。