首页 > 解决方案 > 从 c 中的列表中获取最高值

问题描述

因此,我在使用 C# 程序时遇到了一些麻烦,该程序旨在对列表中的 8 个高度值求和。

该程序通过声明一个变量来工作currenthigh,该变量存储来自gradelist. 然后它将自己与该值进行比较,abshigh以查看它是否大于已建立的最高值。如果是,则设置currenthigh为新的最高值。

一旦循环遍历列表并确认最高值,它会将其添加到uppertotal变量中并使用ejector变量将其从列表中删除。然后程序迭代,这次没有之前的最高值。它迭代 8 次,最后将前 8 个值添加到uppertotal.

麻烦的是,尽管代码中有删除它的指令,最高变量仍保留在列表中,因此它只是将最高值添加到自身 8 次。

int currenthigh = 0;
int abshigh = 0;
int ejector = 0;
int uppertotal = 0;

for (int g = 0; g < 8; g++)
{
    for (int z = 0; z < gradelist.Count; z++)
    {
        Console.WriteLine("PASS STARTED");
        currenthigh = Convert.ToInt32((gradelist[z]));
        Console.WriteLine("currenthigh" + currenthigh);

        if (currenthigh > abshigh)
        {
            abshigh = currenthigh;
            ejector = z;
        }

    }
    Console.WriteLine("ejector" + ejector);
    uppertotal = uppertotal + currenthigh;

    gradelist.RemoveAt(ejector);
    Console.WriteLine("PASS COMPLETE");
    Console.WriteLine("RESETING");      
}

注意 -gradelist是始终包含至少 12 个项目的整数列表。

标签: c#listloops

解决方案


发生这种情况是因为您没有从成绩单中删除最高值。注意,你把 Z 放在了弹射器中,但是 Z 是成绩表中的一个索引,当你试图删除它时,你什么都没有删除,因为成绩表中没有 Z 作为成员!代替

gradelist.RemoveAt(ejector);

你应该做这个:

gradelist.RemoveAt(gradelist[ejector]);

但我会推荐你​​完全不同的方法。如果你只想得到你的uppertotal,它是gradlist中前8个成员的总和,使用这个简单的技巧:

uppertotal += gradelist.OrderByDescending(p => p).Take(8).Sum();

推荐阅读