如何实现将任意整数回绕到指定数值范围的C#自定义函数
问题根因
- C# 内置的
%取余运算符针对负数操作数会返回负的余数,原实现直接对余数取Math.Abs会破坏偏移量的方向信息 - 原有逻辑错误判断输入值
value本身的正负,实际应该判断的是输入值相对于范围最小值的偏移量的正负 - 偏移回绕的计算逻辑错误,导致最终结果超出指定范围
修正后代码实现
/// <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 less than or equal to 0.</exception> public static int Wrap(this int value, int minimumValue, int length) { if (length <= 0) throw new ArgumentException($"{nameof(length)} must be greater than 0 in order to produce a valid range to wrap across."); // 计算输入值相对于范围最小值的偏移量 int offset = value - minimumValue; // 计算偏移量对范围长度的余数 int remainder = offset % length; // 负余数修正为正 if (remainder < 0) remainder += length; // 叠加最小值得到最终结果 return remainder + minimumValue; }
效果验证
修正后的实现可以覆盖所有测试场景,所有测试用例输出均与预期一致:
| 输入值(value) | 范围最小值(minimumValue) | 范围长度(length) | 预期输出(expected) | 实际输出 |
|---|---|---|---|---|
| 128 | 256 | 128 | 256 | 256 |
| 255 | 256 | 256 | 511 | 511 |
| -3 | 1 | 2 | 1 | 1 |
| -4 | 0 | 2 | 0 | 0 |
| 63 | 128 | 384 | 447 | 447 |
| 300 | 100 | 200 | 100 | 100 |
内容的提问来源于stack exchange,提问作者Matt Arnold
相关产品推荐
相关产品推荐

