,可以通过以下步骤实现:
下面是一个示例代码:
void main() {
List<int> numbers = [5, 2, 9, 1, 7, 6, 3, 8, 4];
List<int> sortedList = List.from(numbers);
sortedList.sort();
double median;
if (sortedList.length % 2 == 1) {
median = sortedList[(sortedList.length / 2).floor()].toDouble();
} else {
int middleIndex = sortedList.length ~/ 2;
median = (sortedList[middleIndex - 1] + sortedList[middleIndex]) / 2;
}
print("中位数: $median");
}
在这个示例中,我们首先定义了一个包含整数的列表numbers。然后,我们使用List.from()方法创建了一个新的列表sortedList,并对其进行排序。接下来,根据sortedList的长度判断中位数是单个元素还是两个元素的平均值,并将结果存储在变量median中。最后,我们打印出中位数的值。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云