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

C#固定长度数组空值被计为0致统计结果异常求助

问题解决思路及代码修正

你的核心问题是统计方法遍历了整个固定长度数组,而实际有效分数只有count个(导入的数量),剩余空位默认值0被纳入计算,导致结果错误。以下是针对性修正:

1. 修正统计方法,仅处理有效分数

修改所有统计函数,新增count参数指定有效元素数量,只遍历前count个元素:

// 计算总分
private double Total(double[] iArray, int count)
{
    double total = 0;
    for (int index = 0; index < count; index++)
    {
        total += iArray[index];
    }
    return total;
}

// 计算平均分
private double Average(double[] iArray, int count)
{
    if (count == 0) return 0; // 避免除以0异常
    double total = Total(iArray, count);
    return total / count;
}

// 计算最高分
private double Highest(double[] iArray, int count)
{
    if (count == 0) throw new ArgumentException("没有有效分数");
    double highest = iArray[0];
    for (int index = 1; index < count; index++)
    {
        if (iArray[index] > highest)
        {
            highest = iArray[index];
        }
    }
    return highest;
}

// 计算最低分
private double Lowest(double[] iArray, int count)
{
    if (count == 0) throw new ArgumentException("没有有效分数");
    double lowest = iArray[0];
    for (int index = 1; index < count; index++)
    {
        if (iArray[index] < lowest)
        {
            lowest = iArray[index];
        }
    }
    return lowest;
}

2. 修改统计方法的调用逻辑

在addFileButton_Click方法中,调用统计函数时传入有效分数的数量count:

// 替换原统计调用代码
highestScore = Highest(scores, count);
lowestScore = Lowest(scores, count);
averageScore = Average(scores, count);
totalScore = Total(scores, count);

3. 进阶优化:用动态列表替代固定数组

固定长度数组天生不适合元素数量不确定的场景,改用List<double>可彻底避免空位问题,代码更简洁健壮:

private void addFileButton_Click(object sender, EventArgs e)
{
    try
    {
        List<double> scores = new List<double>(); // 动态列表,自动适配元素数量
        double highestScore;
        double lowestScore;
        double averageScore;
        double totalScore;

        if (openFile.ShowDialog() == DialogResult.OK)
        {
            // 读取文件并过滤有效分数
            foreach (var line in File.ReadLines(openFile.FileName))
            {
                if (double.TryParse(line, out double score) && score >= 0 && score <= 100)
                {
                    scores.Add(score);
                }
                else
                {
                    MessageBox.Show($"无效分数:{line},已跳过");
                }
            }
        }
        else
        {
            MessageBox.Show("操作已取消。");
            return;
        }

        // 显示分数
        scoreListBox.Items.Clear();
        foreach (var score in scores)
        {
            scoreListBox.Items.Add(score.ToString());
        }

        // 用LINQ简化统计(需添加using System.Linq;)
        totalScore = scores.Sum();
        averageScore = scores.Any() ? scores.Average() : 0;
        highestScore = scores.Any() ? scores.Max() : 0;
        lowestScore = scores.Any() ? scores.Min() : 0;

        // 显示结果(格式化小数更友好)
        highesScoreLabel.Text = highestScore.ToString();
        lowestScoreLabel.Text = lowestScore.ToString();
        averageTestScoreLabel.Text = averageScore.ToString("F2");
        totalTestScoresLabel.Text = totalScore.ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

优化点说明

  • List<double>自动扩容,无需提前设定固定长度
  • 新增double.TryParse和分数范围校验,避免无效数据导致程序崩溃
  • 使用LINQ内置方法简化统计逻辑,减少重复代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:20:26