如何在MiniZinc中遍历数组并输出结果?
在MiniZinc中遍历数组并输出元素的正确方法
你的代码存在几处问题,导致输出不符合预期,以下是修正后的实现方式:
问题分析
- 数组引用错误:代码中写的
array[c]应该是你定义的数组名my_array[c] - 变量插值错误:字符串中的
c未使用MiniZinc的插值语法,需要写成\(c)才能输出变量的实际值 - Output循环写法错误:
forall不能直接用于生成output的字符串列表,需使用列表推导式或结合join函数来生成输出内容
修正后的代码
方法1:使用列表推导式生成输出列表
array[1..4] of int: my_array = [4,5,1,3]; output [ "element index \(c) is: \(my_array[c])\n" | c in 1..4 ];
方法2:结合join函数和循环
array[1..4] of int: my_array = [4,5,1,3]; output [ join("\n", [ "element index \(c) is: \(my_array[c])" | c in 1..4 ]) ++ "\n" ];
输出结果
运行上述代码后,会得到符合逻辑的正确输出:
element index 1 is: 4 element index 2 is: 5 element index 3 is: 1 element index 4 is: 3
(注:你提供的期望输出中所有索引都写为1,应该是笔误,正确索引会对应数组的1到4)
内容的提问来源于stack exchange,提问作者Saadoun
相关产品推荐
相关产品推荐

