[英]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);
}
注意,我將min
, max
和total
的類型設為long
以避免潛在的溢出。 total
因為將足夠的整數或大整數求和可能導致一個不適合int
。 更糟糕的情況是一個大小為int.MaxValue
的數組,其中所有項目均為int.MaxValue
, total
int.MaxValue * int.MaxValue
為int.MaxValue * int.MaxValue
,並且將適合long
。 min
和max
很long
因為我們將它們相加,並且int.MaxValue + int.MaxValue
不適合int
,但是適合long
。 同樣的想法也適用於int.MinValue
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.