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

C# 不使用数组仅通过循环计算输入分数最值的实现问题

不使用数组实现分数最值计算的解决方案

你不需要存储所有分数,仅需维护两个变量记录当前遍历到的最高分、最低分,每次录入新分数时实时对比更新即可,实现逻辑如下:

完整实现代码

using System;

class Program
{
    static void Main()
    {
        int MarkNumber;
        Console.Write("有多少个分数?: ");
        MarkNumber = Convert.ToInt32(Console.ReadLine());

        // 定义存储最值的变量
        int maxScore = 0;
        int minScore = 0;

        for (int SchoolM = 0; SchoolM < MarkNumber; SchoolM++)
        { 
            Console.Write("请输入分数: ");
            int currentScore = Convert.ToInt32(Console.ReadLine());
            
            // 第一次录入的分数直接作为初始最值
            if (SchoolM == 0)
            {
                maxScore = currentScore;
                minScore = currentScore;
            }
            else
            {
                // 大于当前最高分则更新最高分
                if (currentScore > maxScore)
                {
                    maxScore = currentScore;
                }
                // 小于当前最低分则更新最低分
                if (currentScore < minScore)
                {
                    minScore = currentScore;
                }
            }
        }

        // 输出结果
        Console.WriteLine($"最高分是:{maxScore}");
        Console.WriteLine($"最低分是:{minScore}");
    }
}

逻辑说明

  • 第一次循环录入第一个分数时,直接把该值同时赋值给maxScore和minScore,避免初始值设置不合理导致计算错误
  • 后续每次录入新分数,仅需要和当前的最值做两次对比,符合条件就更新对应变量,全程不需要额外存储历史分数
  • 如果需要支持小数分数,把int类型替换为double即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:42:03