c# - 从 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 个项目的整数列表。
解决方案
发生这种情况是因为您没有从成绩单中删除最高值。注意,你把 Z 放在了弹射器中,但是 Z 是成绩表中的一个索引,当你试图删除它时,你什么都没有删除,因为成绩表中没有 Z 作为成员!代替
gradelist.RemoveAt(ejector);
你应该做这个:
gradelist.RemoveAt(gradelist[ejector]);
但我会推荐你完全不同的方法。如果你只想得到你的uppertotal,它是gradlist中前8个成员的总和,使用这个简单的技巧:
uppertotal += gradelist.OrderByDescending(p => p).Take(8).Sum();
推荐阅读
- faunadb - ABAC 权限对于读取和写入的工作方式不同
- cmake - cMake 从子项目安装第三方库
- android - 如何从谷歌脚本向WhatsApp组发送消息?
- reactjs - 从使用 CRA 创建的 Firebase 托管 React 应用程序访问外部 API
- javascript - NaN 倒数计时器 javascript
- sql-server - SQL Server - 视图中的 CTE 和删除
- python - Pandas - 确定日期是否在用户的多个开始停止范围内
- powershell - 无法模拟 start-process powershell {} 命令?
- cmake - CMake:如何将具有不同文件名的导入库链接到库名
- javascript - Javascript:如何打印包含回车的字符串的原始内容?