You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

读取含行列数的文本文件并构建矩阵的技术实现咨询

Is This Matrix Construction Requirement Achievable? (And Fixed Pascal Code)

Absolutely, your requirement is totally achievable! Let's first break down the issues in your current code, then walk through a corrected version that meets your needs perfectly.

What's Off With Your Existing Code?

  • The while not eoln(datoteka) loop keeps reading values into m and n until the end of the first line. This means by the loop's end, m and n will get overwritten to the last two numbers in the line (instead of the first two, which are your intended row and column counts).
  • The repeat-until block has invalid Pascal syntax (read eoln(n) isn't a valid statement) and no logical purpose for reading matrix elements.
  • There’s no code to actually construct or populate the matrix, and you never close the file—this is a basic best practice to avoid resource leaks.

Corrected Pascal Code

Here’s a fully functional version that reads the matrix dimensions and populates the matrix correctly:

Program MatrixBuilder;
const MAX_SIZE = 100; // Clearer constant name for maximum matrix size
type Matrix = array[1..MAX_SIZE, 1..MAX_SIZE] of Integer;
var
  datoteka: Text;
  m, n: Integer;      // m = rows, n = columns
  i, j: Integer;      // Loop counters for rows and columns
  matrix: Matrix;     // The matrix we'll build
begin
  // Link the file variable to your input file
  Assign(datoteka, 'datoteka.txt');
  Reset(datoteka);
  
  // Step 1: Read the first two values as matrix dimensions (rows m, columns n)
  Read(datoteka, m, n);
  
  // Step 2: Read the next m*n values and populate the matrix row by row
  for i := 1 to m do
    for j := 1 to n do
      Read(datoteka, matrix[i][j]);
  
  // Optional: Print the matrix to verify it's built correctly
  Writeln('Successfully built matrix (', m, ' rows, ', n, ' columns):');
  for i := 1 to m do
  begin
    for j := 1 to n do
      Write(matrix[i][j], ' ');
    Writeln; // New line after each row
  end;
  
  // Always close the file when done
  Close(datoteka);
end.

How It Works With Your Example Input

For your sample input text: 4 3 1 2 3 5 6 7 9 10 8 1 11 13

  • The code first reads m=4 (rows) and n=3 (columns)
  • Then it reads the next 4*3=12 values and fills the matrix row by row
  • The verification output will be:
Successfully built matrix (4 rows, 3 columns):
1 2 3 
5 6 7 
9 10 8 
1 11 13 

内容的提问来源于stack exchange,提问作者ZoranSRB17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:45:09