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

如何在MiniZinc中遍历数组并输出结果?

在MiniZinc中遍历数组并输出元素的正确方法

你的代码存在几处问题,导致输出不符合预期,以下是修正后的实现方式:

问题分析

  1. 数组引用错误:代码中写的array[c]应该是你定义的数组名my_array[c]
  2. 变量插值错误:字符串中的c未使用MiniZinc的插值语法,需要写成\(c)才能输出变量的实际值
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:16:12