繁体   English   中英

在2D数组中添加最大值和最小值,不包括最高和最低整数

[英]adding maximum and minimum values in a 2D array, excluding the highest and lowest integers

我有一个2D数组,我想分别输出每个数组的值的总和,但也要从该总和的计算中排除最大值和最小值。 如果数组= {{2,3,4,5},{4,5,6,7}},则为EG。 那么代码应从第一个数组中排除2和5,仅相加并输出9(3 + 4),然后为第二个数组输出11(5 + 6)。 同样,如果数组包含2个或多个最小值,而两个或多个包含最大值,则如果数组= {2,2,3,4,5,6,6 }代码应输出20(2 + 3 + 4 + 5 + 6)。

我本人尝试对此进行编码,但是我的值没有显示出来。 我认为这可能与我的scores_total等于0有关,但我不知道该如何声明。

任何帮助,将不胜感激。

结果数组存储在main中

static void JudgesTotal(int[,] results)
{
    int Minimum = results[0, 0];
    int Maximum = results[0, 0];
    int score_total = 0;

    for (int i = 0; i < results.GetLength(0); i++)
    {
        score_total = score_total + results[i, j];
        if (Minimum > results[i, j])
        {
            Minimum = results[i, j];
        }

        if (Maximum < results[i, j])
        {
            Maximum = results[i, j];
        }

        score_total = score_total - (Maximum - Minimum);

        if (results[i, j] > results[i, j] + 1)
        {
            Console.Write("{0}", score_total);
        }
    }
}

您的代码有很多问题。 首先,您无需在下一个数组的开始处重置“ Minimum和“ Maximum ”。 其次,您无需在每个新数组的开始处重置score_total 接下来,您对最大值的比较是错误的。 最后,在内循环完成之后,您必须减去最小值和最大值。 这是解决所有这些问题的示例。 我也不清楚你为什么在其中有if(result[i,j] > result[i,j] + 1) ,因为只有在result[i,j]int.MaxValue result[i,j]它才会为true

for(int i = 0; i < results.GetLength(0); i++)
{
    if(results.GetLength(1) <= 2)
    {
        //There are either 0 items which would sum to 0
        //Or 1 item which is both the min and max and the sum should be 0
        //Or 2 items where one is the min and the other the max and the sum should be 0
        Console.WriteLine(0);
        continue;
    }

    long min = results[i,0];
    long max = results[i,0];
    long total = 0;
    for(int j = 0; j < results.GetLength(1); j++)
    {
        total += results[i,j];
        if(results[i,j] < min)
            min = results[i,j];
        if(max < results[i,j])
            max = results[i,j];
    }
    total -= (min + max);
    Console.WritLine(total);
}

注意,我将minmaxtotal的类型设为long以避免潜在的溢出。 total因为将足够的整数或大整数求和可能导致一个不适合int 更糟糕的情况是一个大小为int.MaxValue的数组,其中所有项目均为int.MaxValuetotal int.MaxValue * int.MaxValueint.MaxValue * int.MaxValue ,并且将适合long minmaxlong因为我们将它们相加,并且int.MaxValue + int.MaxValue不适合int ,但是适合long 同样的想法也适用于int.MinValue

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM