[英]Why does the function return 0?
I have this function that should take a matrix, compare the diagonal elements of the matrix and find the smallest one.我有这个 function 应该采用矩阵,比较矩阵的对角元素并找到最小的元素。
Here it should compare y[0][1]
and y[1][0]
.在这里它应该比较
y[0][1]
和y[1][0]
。
#include <iostream>
int Min(int, int [][2]);
using namespace std;
int main() {
int min, y[2][2];
y[0][0]=5;
y[0][1]=4;
y[1][0]=-9;
y[1][1]=0;
min = Min(2, y);
cout<<min;
return 0;
}
int Min(int k, int x[][2]){
int min=x[0][0];
for(int i=0; i<k;i++){
if(x[i][i]<min){
min=x[i][i];
}
}
return min;
}
It always returns 0. Why?它总是返回 0。为什么?
Here it should compare y[0][1] and y[1][0].
这里它应该比较 y[0][1] 和 y[1][0]。
Your function goes through the diagonal of the matrix, it hence checks y[0][0]
and y[1][1]
.您的 function 穿过矩阵的对角线,因此检查
y[0][0]
和y[1][1]
。 They are 5 and 0. The result is zero, which is to be expected.它们是 5 和 0。结果为零,这是意料之中的。
Here it should compare
y[0][1]
andy[1][0]
.在这里它应该比较
y[0][1]
和y[1][0]
。
But that's not what you say here:但这不是你在这里所说的:
int min=x[0][0];
or here:或在这里:
if(x[i][i]<min){
min=x[i][i];
}
Since i
cannot be both 0 and 1 at the same time, this accesses x[0][0]
and x[1][1]
.由于
i
不能同时为 0 和 1,因此访问x[0][0]
和x[1][1]
。
And for those elements, 0 is the correct minimum.对于这些元素,0 是正确的最小值。
As a side note, your Min
function can only work with matrices of size 2, so the k
parameter is unnecessary.作为旁注,您的
Min
function 只能使用大小为 2 的矩阵,因此不需要k
参数。 Multi-dimensional arrays are annoying like that.多维 arrays 就是这么烦人。
To iterate over all items instead of just [0][0]
and [1][1]
you need to do:要遍历所有项目,而不仅仅是
[0][0]
和[1][1]
,您需要执行以下操作:
for(int i=0; i<k; i++)
{
for(int j=0; j<k; j++)
{
if(x[i][j]<min)
{
min=x[i][j];
}
}
}
int Min(int k,const int x[][2])
{
int min=x[0][0];
for(int i=0; i<k;i++)
{
for(int j=0;j<k;j++)
{
if(x[i][j]<min)
{
min=x[i][j];
}
}
}
Earlier it was always showing zero because it had a mess with the column index.早些时候它总是显示为零,因为它与列索引混淆。 Outer for loop iterates k-1 times with first iteration at i=0, and second at i=1 and during both iterations it assigns the same index to both row and column(ie, x [0][0] and x[1][1]).
外部 for 循环迭代 k-1 次,第一次迭代在 i=0 时,第二次在 i=1 时,在两次迭代期间,它为行和列分配相同的索引(即 x [0][0] 和 x[1 ][1])。 Perhaps it must assign the index x[0][0], x[0][1], x[1][0], x[1][1].
也许它必须分配索引 x[0][0]、x[0][1]、x[1][0]、x[1][1]。 Earlier, it had only two iterations(the outer for loop) but now it takes four iterations assigning the appropriate index to both column and rows the efficient number of times.
早些时候,它只有两次迭代(外部 for 循环),但现在需要四次迭代才能将适当的索引分配给列和行的有效次数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.