使用Mod在最小和最大之间进行数学循环? [英] Math Looping Between Min and Max Using Mod?

查看:73
本文介绍了使用Mod在最小和最大之间进行数学循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个微小的(或可能不是那么小的)公式,该公式将包含一个介于设定的最小值和最大值之间的数字,但是还要循环这些数字,以便在超出范围时不会被裁剪.到目前为止,这就是我所拥有的.

i'm attempting to build a tiny (or perhaps not so tiny) formula that will contain numbers between a set min and max, but also loop these numbers so they are not clipped if they are outside of the range. so far, this is what i have.

min1 = 10
max1 = 90

val1 = 92
//will make 11, which is what i want since it loops

formula:  min(max(min1,min(val1,max1)),mod(val1,max1)+min1)

但是,我也希望它向另一个方向循环,因此,如果val1为5,即min1之外的-5,它将变为86.

however, i'd like it to loop the other direction also, so that if val1 is 5, which is -5 outside of min1, it will become 86.

我遇到的另一个问题是

max1 % max1 != max1

如我所愿,因为最大值是范围的一部分

as i want it to, since the max is part of the range

试图弄清楚,这是一些基于带循环范围的期望输出的示例

trying to be clear, here are some examples of desired output based on a range with looping

min1 = 10
max1 = 90
----------------------------------------------
val1 = 30    //within range: stays as 30 
val1 = 90    //within range: stays as 90
val1 = -6    //below range: loops to becomes 75
val1 = 98    //above range: loops to becomes 17
val1 = 91    //above range: loops to becomes 10

我不想使用一系列的if/else语句,但是如果绝对需要的话可以使用.那有可能吗?

i'd like not to resort to using a series of if/else statements, but one would be fine if it's absolutely required. is that even possible?

推荐答案

int loop(int val, int min, int max)
{
    int p = max-min+1;
    int mod = (val-min)%p;
    if(mod<0)
        mod += p;
    return min+mod;
}

这篇关于使用Mod在最小和最大之间进行数学循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆