Solved Modulo not working correctly (Clamp)

Various / CUSTOM BUILT
February 21, 2017 at 05:44:18
Specs: Windows 10 Pro, Intel i7 4770k, 32GB 1600MHz RAM
I'm trying to get a number to stay within a given range, it sort of works using modulo, but when I run into negative numbers, things get troublesome.

Example:
I have a number, say 3, then I'll add a given number, say 40, to that number. This works with:
set /a num=3+40%%30
However when I do:
set /a num=3-40%%30
I get a negative number, though instead of going down below zero I want it to start from 30 and go down from there.

Basically a clamp function for batch.

Don't worry if plan A fails, there are 25 more letters in the alphabet ;)


See More: Modulo not working correctly (Clamp)

Report •

#1
February 21, 2017 at 15:40:35
✔ Best Answer
Clamp wouldn't wrap, but you would just implement it with two IFs.
SET /A num= 3 + 40 %% 30
IF %num% LSS 0 SET num=0
IF %num% GTR 30 SET num=30

What you're looking for is a wrap. If you're expected to encounter negative numbers, you'll need to do something like this.
SET /A num= ((3-40%%30) + 30) %% 30

How To Ask Questions The Smart Way


Report •
Related Solutions


Ask Question