嵌套for循环中的“除以零”错误

时间:2013-03-02 16:44:57

标签: php for-loop division zero

此脚本的目的:

编写一个从1到10计数的脚本,步长为1.对于每个数字,显示是否相同 number是奇数或偶数,如果数字是素数,也会显示一条消息。 在HTML表格中显示此信息。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Exercise 1</title>
<link rel="stylesheet" type="text/css" href="common.css" />
<style type="text/css">
  th { text-align: left; background-color: #999; }
  th, td { padding: 0.4em; }
  tr.alt td { background: #ddd; }
</style>
</head>
<body>

<h2>Exercise 1</h2>

<table cellspacing="0" border="0" style="width: 20em; border: 1px solid #666;">
  <tr>
    <th>Number</th>
    <th>Parity</th>
    <th>Primality</th>
  </tr>
    <?php 
    $n=10;
    for ($i=1;$i<=$n;$i++){
    echo ($i%2 != 0)? '<tr class = "alt">':'<tr>'; ?>
    <td><?php echo $i; ?></td>
    <td><?php echo ($i%2 != 0)? "Odd":"Even";?></td>
    <td><?php 

    $k=0;
    for ($j=1;$j<=$i;$j++){
        if ($i%$j=0) $k++; //Where the error occurs
    }
    echo ($k=2 || $k=1)?"Prime":"Composite";?>
    </td></tr>
    <?php
    }
    ?>
</table>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

if ($i%$j=0)应该是if ($i%$j==0)

答案 1 :(得分:0)

$i%$j=0

$j指定为0,然后尝试$i % 0;

你想要

($i % $j) == 0

echo以同样的方式出现了另一个错误。

还要考虑使用空格格式化代码以使其更具可读性。