這段代碼應該在一個小數陣列中搜索處于指定范圍內的元素,并回傳符合范圍條件的元素的出現次數。
問題是,我在訪問鋸齒形陣列時遇到了困難,我的代碼:
public static int GetDecimalsCount(span class="hljs-built_in">decimal[] arrayToSearch, decimal[] [] ranges)?
{
if (arrayToSearch is null)
{
throw new ArgumentNullException(nameof(arrayToSearch))。
}
else if ( ranges is null)
{
throw new ArgumentNullException(nameof(range))。
}
else; }
{
int sum = 0;
for (int i = 0; i < arrayToSearch.Length; i )
{
for (int j = 0; j < ranges.Length; j )
{
for (int n = 0; n < ranges[j] .Length; n )
{
if (arrayToSearch[i] >= ranges[j][n] && arrayToSearch[i] <= ranges[j][n 1] )
{
sum ;
}
}
}
}
return sum;
}
}
范圍是從最低到最高,所以它將總是兩個小數的陣列
我也相信這至少應該是可行的:if(arrayToSearch[i] > = ranges[j][0] && arrayToSearch[i] <= ranges[j][1] )
它是如何不比較陣列的,我不明白。
編輯1:測驗中的陣列資料
插入一些測驗代碼,如果你需要完整的代碼,我可以發送。它有點長,而且有其他作業的不重要的測驗案例。
private static readonly decimal[] ArrayWithFiveElements = { 0. 1m, 0.2m, 0.3m, 0.4m, 0.5m };
private static readonly decimal[ ] ArrayWithFifteenElements = { decimal. MaxValue, -0.1m, -0.2m, decimal.One, -0. 3m, -0.4m, -0.5m, 十進制.零, 0.1m, 0。 2m, 0.3m, 0.4m, 0。 5m, decimal.MinusOne, decimal.MinValue };
[測驗]
public void DecimalCounter_FiveElementsOneRange_ReturnsResult()
{
//Arrange
decimal[] [] ranges =
{
new[] { 0.1m, 0.2m },
};
// Actint actualResult = DecimalCounter.GetDecimalsCount(DecimalCounterTests.ArrayWithFiveElements, ranges)。
// Assert
Assert.AreEqual(2, actualResult)。
}
[測驗]
public void DecimalCounter_FiveElementsTwoRanges_ReturnsResult()
{
//Arrange
decimal[] [] ranges =
{
new[] { 0.1m, 0.2m },
new[] { 0.4m, 0.5m },
};
// Actint actualResult = DecimalCounter.GetDecimalsCount(DecimalCounterTests.ArrayWithFiveElements, ranges)。
// Assert
Assert.AreEqual(4, actualResult)。
uj5u.com熱心網友回復:
在修正了評論中指出的錯誤后,我沒有發現代碼中有任何問題;https://dotnetfiddle.net/F6Yjy0
public static int GetDecimalsCount(span class="hljs-built_in">decimal[] arrayToSearch, decimal[] [] ranges)?
{
if (arrayToSearch == null)
{
throw new ArgumentNullException(nameof(arrayToSearch)) 。
}
else if ( ranges == null)
{
throw new ArgumentNullException(nameof(range))。
}
else; }
{
int sum = 0;
for (int i = 0; i < arrayToSearch.Length; i )
{
for (int j = 0; j < ranges.Length; j )
{
//for (int n = 0; n < ranges[j].Length; n )
//{
if (arrayToSearch[i] >= ranges[j][0] && arrayToSearch[i] <= ranges[j][1] )
{
sum ;
}
//}。
}
}
return sum;
}
}
最里面的回圈是相當無意義的;它只運行一次,可以用索引0/1來代替。去掉它還可以消除OOB的問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/309998.html
標籤:
上一篇:C 程式過早結束
下一篇:多個下拉選單沒有重復的值
