【问题标题】:Multiplication Table PHP乘法表 PHP
【发布时间】:2020-12-06 18:04:22
【问题描述】:

我想创建一个带有自定义函数的乘法表,并从用户那里获取行数和列数,如果每一行都是偶数,那么它的字段将是红色(背景),如果是奇数它会有一个绿色背景,我也写了一些代码,但我不确定它是否正确:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
    <form method="post">
        <input type="number" name="rows" placeholder="Rows">
        <input type="number" name="columns" placeholder="Columns">
        <button type="submit" name="button">
            Create 
        </button>
    </form>
    <table border="1px">
        <?php

        if (isset($_POST["button"])) {

            $userRows = $_POST["rows"];
            $userColumns = $_POST["columns"];

            function multiplicationTable($rows, $columns)
            {
                $zarb = $rows * $columns;
                return $zarb;
            }

            $x = 1;
            while ($x <= $userRows) {
                echo "<tr>";
                $y = 1;
                while ($y <= $userColumns) {
                    if ($x % 2 == 0) {
                        echo "<td style='background-color: red;'>" . multiplicationTable($x, $y) . "</td>";
                    } else {
                        echo "<td style='background-color: green;'>" . multiplicationTable($x, $y) . "</td>";
                    }
                    $y++;
                }
                $x++;
                echo "</tr>";
            }
        }
        ?>
    </table>
</body>

</html>

【问题讨论】:

  • 为了可读性,您可能希望使用for() 循环而不是while 循环。您可能希望将名称从 $x$y 更改为 $r/$c$row/$column
  • 你有什么问题?当你尝试你的脚本时,你得到了什么结果?
  • “如果每一行都是偶数”是什么意思?

标签: php multiplication


【解决方案1】:

把while循环改成这样怎么样:

while ($x <= $userRows) {
    echo "<tr>";
    $y = 1;
    while ($y <= $userColumns) {
        
        $val = multiplicationTable($x, $y);
        
        if ($val % 2 == 0) {
            echo "<td style='background-color: red;'>" . $val . "</td>";
        } else {
            echo "<td style='background-color: green;'>" . $val . "</td>";
        }
        $y++;
    }
    $x++;
    echo "</tr>";
}

【讨论】:

    【解决方案2】:
    【解决方案3】:

    最终结果在这个链接中,即使有些数字是偶数,它们仍然显示为绿色,我不知道该怎么办

    https://imgur.com/D1Sweee

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      相关资源
      最近更新 更多