You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现将任意整数回绕到指定数值范围的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)实际输出
128256128256256
255256256511511
-31211
-40200
63128384447447
300100200100100

内容的提问来源于stack exchange,提问作者Matt Arnold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:24:03