我正在使用我的sql表中的二维数据的欧几里德距离公式实现k-最近邻alog。事情看起来还不错,即使它表现出奇怪的行为。
代码:
$result1 = mysqli_query($con,"SELECT pcount, ncount from test");
$result2 = mysqli_query($con,"SELECT pcount, ncount from test");
$i = 0;
$min = 0;
while ($row1 = @mysqli_fetch_array($result1))
{
$pcount = $row1['pcount'];
$ncount = $row1['ncount'];
echo "pcount is $pcount<br/>";
echo "ncount is $ncount<br/></br>";
$a[$i] = $pcount ;
$b[$i] = $pcount ;
$j = 0;
while ($row2 = @mysqli_fetch_array($result2))
{
echo "j is $j <br/>";
$a[$j] = $row2['pcount'];
$b[$j] = $row2['ncount'];
$diff = sqrt(($a[$i] - $a[$j])^2 + ($b[$i] - $b[$j])^2 );
$j= $j + 1;
echo "$diff <br>";
}
echo "i is $i <br/>";
$i = $i + 1;
}
它给出了这个结果:
j is 0
Difference : 0
j is 1
Difference : 1.4142135623731
j is 2
Difference : 0
j is 3
Difference : 0
j is 4
Difference : 1.4142135623731
j is 5
Difference : 1.4142135623731
j is 6
Difference : 1.4142135623731
i is 0
在表格中我总共有8行,但上面的结果只有7行。为什么呢?
首先对$i = 0
on执行while循环,其余i = 1到7无操作。有人可以告诉我什么是虫子吗?
表中的数据是
pcount ncount
20 80
21 79
20 80
21 79
19 81
20 80
20 80
20 80
fallens回答后的结果:
j is 0
Difference : 0
j is 1
Difference : NAN
j is 2
Difference : 0
j is 3
Difference : NAN
j is 4
Difference : 1.4142135623731
j is 5
Difference : 0
j is 6
Difference : 0
j is 7
Difference : 0
i is 0
pcount is 21
ncount is 79
i is 1
pcount is 20
ncount is 80
i is 2
pcount is 21
ncount is 79
i is 3
pcount is 19
ncount is 81
i is 4
pcount is 20
ncount is 80
i is 5
pcount is 20
ncount is 80
i is 6
pcount is 20
ncount is 80
i is 7
答案 0 :(得分:1)
您在内部和外部循环中使用相同的变量。在这两个循环中为row
和result
s尝试不同的变量名称。与result1
一样,row1
表示外部result2
,row2
表示内部循环
它显示7行而不是8行,因为result
的第一行已被外环拾取
试试这段代码:
$result1 = mysqli_query($con,"SELECT pcount, ncount from test");
$i = 0;
$min = 0;
while ($row1 = @mysqli_fetch_array($result1))
{
$pcount = $row1['pcount'];
$ncount = $row1['ncount'];
echo "pcount is $pcount<br/>";
echo "ncount is $ncount<br/></br>";
$a[$i] = $pcount ;
$b[$i] = $pcount ;
$j = 0;
$result2 = mysqli_query($con,"SELECT pcount, ncount from test");
while ($row2 = @mysqli_fetch_array($result2))
{
echo "j is $j <br/>";
$a[$j] = $row2['pcount'];
$b[$j] = $row2['ncount'];
$diff = ($a[$i] - $a[$j])^2 + ($b[$i] - $b[$j])^2;
if( $diff != 0)
$diff = sqrt( $diff );
$j= $j + 1;
echo "$diff <br>";
}
echo "i is $i <br/>";
$i = $i + 1;
}
注意为避免NaN
,请确保($a[$i] - $a[$j])^2 + ($b[$i] - $b[$j])^2
不会产生0。