PHP 程序:将值插入矩阵


2022年3月25日, Learn eTutorial
1512

如何将值插入矩阵?

要将值插入矩阵,首先我们需要将值读入矩阵的行和列。然后通过使用 for 循环,我们需要将值读入行和列的每个位置。例如,如果行数为 3,列数为 3,我们需要将值读入 "(0,0) (0,1) (0,2)(1,0) (1,1) (1,2) (2,0) (2,1) (2,2)"

如何在 PHP 中将值插入矩阵?

要将值插入矩阵,首先我们需要创建一个空数组 a[]。然后我们需要从用户那里接收变量 rowcol 的值,以存储行数和列数。之后,我们需要将值 0 赋给变量 i,并执行循环,直到条件 'i < row' 变为假,并在每次迭代中递增变量 i 的值。在循环块中,我们需要执行另一个循环,其中我们需要将值 0 赋给变量 j,并执行循环,直到条件 'j < col' 变为假,并在每次迭代中递增变量 j 的值。在循环块中,我们需要从用户那里接收值到 array[i][j],循环完成后,我们可以使用 for 循环打印数组 a[] 中的值。

算法

步骤 1: 初始化一个空数组 a[]

步骤 2: 从用户那里接收变量 rowcol 的值,以存储行数和列数

步骤 3: 将值 0 赋给变量 i,并执行子步骤,直到条件 'i < row' 变为假,并在每次迭代中递增变量 i 的值

        (i) 将值 0 赋给变量 j,并执行子步骤,直到条件 'j < col' 变为假,并在每次迭代中递增变量 j 的值

            (a) 从用户那里接收值到数组 a[i][j]

步骤 4: 使用 for 循环打印数组 a[] 中的元素

PHP 源代码

                                          <?php
$a = array();
$flag = true;
$row = readline("Enter the number of rows: \n");
$col = readline("Enter the number of columns: \n");
for ($i = 0; $i < $row; $i++) {
    for ($j = 0; $j < $col; $j++) {
        $a[$i][$j] = readline("Enter the value at position $i $j :  ");
    }
}
echo "The entered matrix is matrix: \n";
for ($i = 0; $i < $row; $i++) {
    for ($j = 0; $j < $col; $j++) {
        echo $a[$i][$j] . " ";
    }
    echo "\n";
}
?>
                                      

输出

Enter the number of rows:  3
Enter the number of columns:  3
Enter the value at position 0 0 :  5
Enter the value at position 0 1 :  6
Enter the value at position 0 2 :  7
Enter the value at position 1 0 :  8
Enter the value at position 1 1 :  4
Enter the value at position 1 2 :  1
Enter the value at position 2 0 :  9
Enter the value at position 2 1 :  3
Enter the value at position 2 2 :  2
The matrix:
5 6 7
8 4 1
9 3 2