Ada程序优化咨询:能否将参数交换逻辑整合入My_Character_Program过程?
问题解答
完全可以将大小判断、参数顺序调整的逻辑整合到My_Character_Program过程内部,优化后的实现不仅更简洁,还能提升过程的复用性——后续其他场景调用该过程时不需要额外处理参数顺序。
另外需要先指出原代码存在的一个bug:原代码循环输出的变量写为A,但循环变量是C,且代码中未定义变量A,会导致编译失败,修改时会同步修复这个问题。
最优实现方案
核心优化点是在My_Character_Program内部用Ada内置的'Min、'Max属性直接获取两个字符的上下界,不需要手写if交换逻辑,代码更简洁易读。
修改后的完整代码如下:
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Float_Text_IO; use Ada.Float_Text_IO; with Ada.Numerics.Float_Random; with Ada.Numerics.Discrete_Random; procedure Probability is subtype My_Characters is Character range 'a' .. 'z'; package My_Random_Character_Package is new Ada.Numerics.Discrete_Random(My_Characters); use My_Random_Character_Package; Gen_1 : My_Random_Character_Package.Generator; procedure My_Character_Program(Char_A, Char_B : in Character) is -- 内部自动处理顺序,拿到上下界 Low : constant Character := Character'Min(Char_A, Char_B); High : constant Character := Character'Max(Char_A, Char_B); begin Put(Low); Put(" "); Put(High); New_Line; Put("All characters between "); Put(Low); Put(" and "); Put(High); Put(":"); for C in Character range Low .. High loop Put(" "); Put(C); -- 修复原代码变量错误的问题 end loop; New_Line; end My_Character_Program; procedure Part_2 is First_Character, Second_Character : Character; begin Put_Line("PART 2:"); Put_Line("Two random characters from a to z will now be generated."); Put("Random characters: "); First_Character := Random(Gen_1); Second_Character := Random(Gen_1); -- 不需要判断顺序,直接传参数即可 My_Character_Program(First_Character, Second_Character); end Part_2; begin -- Reset(Gen_1); Part_2; New_Line(2); end Probability;
优化说明
- 过程复用性提升:
My_Character_Program现在支持任意顺序传入两个小写字母,内部自动处理排序逻辑,所有调用方都不需要额外写判断交换的代码 - 代码简洁度提升:用Ada标准属性
'Min/'Max实现大小判断,比手写if交换逻辑代码量更少,可读性更强 - 修复了原代码中循环输出变量引用错误的问题,保证可正常编译运行
内容的提问来源于stack exchange,提问作者leun
相关产品推荐
相关产品推荐

