[英]How do you create a function to wrap numbers to a specified range?
我正在嘗試創建一個函數,以數學方式將數字下溢或下溢到指定的范圍內。 我Math.Abs
數字都是正數時(取出Math.Abs
(用於正數化負數))但負值或負值的范圍失敗,我認為我能夠Math.Abs
。 我想用數學解決這個問題,但不知道我做錯了什么!
這是我當前對失敗函數的實現:
/// <summary>
/// Wraps a value within the specified range, overflowing or underflowing as necessary.
/// </summary>
/// <param name="value">The number to wrap.</param>
/// <param name="minimumValue">The minimum value in the range.</param>
/// <param name="length">The number of values in the range to wrap across.</param>
/// <returns>The <paramref name="value"/> wrapped to the specified range.</returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="length"/> is <c>0</c>.</exception>
public static int Wrap(this int value, int minimumValue, int length)
{
if (length == 0)
throw new ArgumentException($"{nameof(length)} must not be 0 in order to produce a range to wrap across.");
else
{
var absoluteModulus = System.Math.Abs((value - minimumValue) % length);
return (value < 0 ? length - absoluteModulus : absoluteModulus) + minimumValue;
}
}
以下是當前實現的一些測試數據和結果:
價值 | 最小值 | 長度 | 預期的 | 實際的 | 評論 |
---|---|---|---|---|---|
128 | 256 | 128 | 256 | 256 | 經過 |
255 | 256 | 256 | 511 | 257 | 模數向后下溢! |
-3 | 1 | 2 | 1 | 3 | 不知何故下溢超出范圍! |
-4 | 0 | 2 | 0 | 2 | 再次下溢超出范圍! |
63 | 128 | 384 | 447 | 193 | 128 - 63 == 65, 384 - 65 == 319, 319 + 128 == 447, 不是 193‼ |
300 | 100 | 200 | 100 | 100 | 這個溢出有效! |
您似乎知道%
是余數運算,而不是模數(如在模算術中),但簡單地獲取模數的絕對值是不正確的。 您應該使用此處的答案之一。 例如:
private static int Mod(int k, int n) {
int remainder = k % n;
return (remainder < 0) ? remainder + n : remainder;
}
// ... in the else branch, you can directly do
return Mod(value - minimumValue, length) + minimumValue;
您還以不同方式處理value < 0
。 有一個關於負沒有什么特別的value
。 這里的特殊之處在於負余數,這是一個永遠不會由模運算產生的值。 如果您用檢查替換value < 0
以查看(value - minimumValue) % length
是否為負,您的代碼也會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.