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

C#将List转数组求中位数时报无法将void隐式转换为int[]错误怎么办

报错原因

Array.Sort() 是原地排序方法,没有返回值(返回类型为 void),你尝试将它的执行结果赋值给 int[] 类型的 arrSorted 变量,这就是类型转换报错的直接来源。

修复方案

Array.Sort 会直接修改传入的数组,不需要额外接收返回值,同时调整索引类型、计算逻辑避免额外报错,修改后代码如下:

public static int findMedian(List<int> arr)
{
    int[] asArray = arr.ToArray();
    // 直接对数组排序,无返回值
    Array.Sort(asArray);
    int arrLength = asArray.Length;
    // 数组索引必须为整数类型
    int midIndex = arrLength / 2;
    if (arrLength % 2 == 1)
    {
        // 奇数长度直接取中间位置值
        return asArray[midIndex];
    }
    else
    {
        // 偶数长度取中间两个值的平均值
        return (asArray[midIndex - 1] + asArray[midIndex]) / 2;
    }
}

额外优化说明

  • 原代码用 float 类型存储数组索引,会触发新的类型报错,C# 数组索引仅支持整数类型
  • 整数除法默认向下取整,偶数长度时中间两个数的索引可以直接用 midIndex - 1 和 midIndex 获取,不需要调用 Math.Ceiling 或 Math.Floor 方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:36:07