诊断 NaN 的原因
我想按列对 2D 数组求和并求平均值,如果 e[i][j] 的值大于 0 ,则对其进行计数和求和。但我不知道输出是NaN
, 我该如何解决这个问题?
public class d_2DArray {
public static void main(String [] args){
double[][] e= {{0.0,0.0,0.0,0.0},
{0.0,0.6,0.0,0.0},
{0.0,0.2,0.5,0.1},
{0.0,0.2,0.5,0.4},
{0.0,0.2,0.5,0.7},
{0.0,0.0,0.0,0.9}};
double[] avg= new double[4];
double[] sum= new double[4];
int i,j,k=0;
int[][] x=new int [6][4] ;
//average of column
for(j=1;j<e[1].length;j++){
sum[j]=0.0;
for( i= 1; i < e.length; i++)
if(x[i][j]==1){
sum[j] +=e[i][j];
k++;
}
avg[j]= sum[j]/k ;
System.out.println("Average j="+avg[j]);
}
}
}
I want to sum and average of 2D array by column and if the value of e[i][j]
more then 0 , count and sum it. But I don't know the output is NaN
,
how can I fix this?
public class d_2DArray {
public static void main(String [] args){
double[][] e= {{0.0,0.0,0.0,0.0},
{0.0,0.6,0.0,0.0},
{0.0,0.2,0.5,0.1},
{0.0,0.2,0.5,0.4},
{0.0,0.2,0.5,0.7},
{0.0,0.0,0.0,0.9}};
double[] avg= new double[4];
double[] sum= new double[4];
int i,j,k=0;
int[][] x=new int [6][4] ;
//average of column
for(j=1;j<e[1].length;j++){
sum[j]=0.0;
for( i= 1; i < e.length; i++)
if(x[i][j]==1){
sum[j] +=e[i][j];
k++;
}
avg[j]= sum[j]/k ;
System.out.println("Average j="+avg[j]);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里 k 的值在程序结束时仍然为 0,因此将 0 除以 0 得到 NaN。
here value of k remains 0 at the end of the programm so dividing 0 by 0 gives you NaN.
这段代码几乎有太多问题,无法简单回答。
if(x[i][j]==1)< /code> 永远不会为真
sum[j] / k
始终为 0 / 0,即 NaNThis code almost too many problems for a simple answer.
if(x[i][j]==1)
is never truesum[j] / k
is always 0 / 0, which is NaN首先,如果你想读取所有数组,for 循环的索引应该从 0 开始,而不是从 1 开始。
在这一行中,
您说仅当 x[i][j]==1 时才求和,但尚未使用任何值初始化该数组。因此 k 永远不会更新,所以最后你除以 0,这就是为什么你得到 NaN
First of all, the indexes of your for loops should start with 0 and not with 1 if you want to read all the array.
In this line
you are saying you are going to sum only when x[i][j]==1 but you have not initialized that array with any value. Thus k is never updated so at the end you are dividing by 0 and that is why you are getting NaN
第一个问题是
条件永远不会满足。当您初始化数组 x 时,它是一个原始数组,并且 x 的每个元素都被初始化为 0.0,现在上述条件永远不会满足,因此 sum 数组永远不会更新。这意味着 sum 数组的每个元素也被初始化为零。最后当 u 除 0/0 时,结果为 si Nan (k 永远不会增加,因为条件永远不会满足)
First Problem is
The condition never satisfies. When you initialized array x, its a primitive array and every alement of x was initialized to 0.0, Now the above condition never satisfies so array of sum is never updated. This means every element of sum arrray is also initialized to zero. at the end when u divide 0/0, result si Nan (k is never incremented as condition never satisfies)