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

Pascal代码触发Runtime error 106,新手求助故障排查

解决Pascal运行时错误106及代码问题分析

刚接触Pascal就碰到运行时错误确实挺闹心的,我来帮你捋清楚问题出在哪,怎么修复~首先,Runtime error 106对应的是「无效浮点运算操作」,不过从你的代码片段来看,更可能是代码里的拼写失误、类型定义问题间接触发了这个错误。

先看看你的代码里的几个关键问题:

  • 类型定义逻辑错误:你把ArrayOfPersons定义成了record类型,但名字明显暗示它应该是数组类型。正确的写法应该先定义单个人员的记录结构,再基于这个结构定义数组:

    type
      Person = record
        name: String;
        age: Integer; // 年龄用整数类型更合理,别用String
      end;
      ArrayOfPersons = array[1..2] of Person; // 对应你要写入的2个人员,也可以用动态数组`array of Person`
    
  • 代码拼写失误:你最后一行的WriteLn(myFil...明显是myFile的拼写不完整,这种未完成的变量名会导致编译器无法识别,运行时会因为内存访问异常或未定义变量触发错误。

  • 数据类型不匹配:你写入文件的年龄是整数(比如28),但原记录里把age定义成了String,后续如果直接读取整数到字符串字段,部分Pascal编译器会在类型转换时出错,这也可能是触发Runtime error 106的原因之一。

下面是修复后的完整代码示例,包含写入和读取文件的完整逻辑:

program BasicReadWrite;
type
  Person = record
    name: String;
    age: Integer;
  end;
  ArrayOfPersons = array[1..2] of Person;

procedure WriteLinesToFile(var myFile: TextFile);
begin
  WriteLn(myFile, 2); // 先写入人员总数,方便后续读取
  WriteLn(myFile, 'Fred Smith');
  WriteLn(myFile, 28);
  WriteLn(myFile, 'Jill Jones');
  WriteLn(myFile, 32); // 补充Jill的年龄,保证数据完整
end;

procedure ReadLinesFromFile(var myFile: TextFile; var persons: ArrayOfPersons);
var
  i, count: Integer;
begin
  ReadLn(myFile, count);
  for i := 1 to count do
  begin
    ReadLn(myFile, persons[i].name);
    ReadLn(myFile, persons[i].age);
  end;
end;

var
  outputFile: TextFile;
  persons: ArrayOfPersons;
begin
  // 写入文件流程
  Assign(outputFile, 'persons.txt');
  Rewrite(outputFile);
  WriteLinesToFile(outputFile);
  Close(outputFile);

  // 读取文件并输出流程
  Assign(outputFile, 'persons.txt');
  Reset(outputFile);
  ReadLinesFromFile(outputFile, persons);
  Close(outputFile);

  // 打印读取到的信息
  Writeln('读取到的人员信息:');
  Writeln('1. 姓名: ', persons[1].name, ',年龄: ', persons[1].age);
  Writeln('2. 姓名: ', persons[2].name, ',年龄: ', persons[2].age);
end.

简单总结下错误触发的核心原因:你代码里的myFil...拼写错误是直接诱因,而类型定义和数据类型不匹配的问题则会在后续操作中持续引发异常。修复这些点后,Runtime error 106应该就能解决了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:23:03