Recognizing when to use the modulus operator

前端 未结 19 996
醉梦人生
醉梦人生 2020-11-29 16:40

I know the modulus (%) operator calculates the remainder of a division. How can I identify a situation where I would need to use the modulus operator?

I know I can u

19条回答
  •  悲&欢浪女
    2020-11-29 17:13

    Modulus is also very useful if for some crazy reason you need to do integer division and get a decimal out, and you can't convert the integer into a number that supports decimal division, or if you need to return a fraction instead of a decimal.

    I'll be using % as the modulus operator

    For example

    2/4 = 0

    where doing this

    2/4 = 0 and 2 % 4 = 2

    So you can be really crazy and let's say that you want to allow the user to input a numerator and a divisor, and then show them the result as a whole number, and then a fractional number.

    whole Number = numerator/divisor
    fractionNumerator = numerator % divisor
    fractionDenominator = divisor
    

    Another case where modulus division is useful is if you are increasing or decreasing a number and you want to contain the number to a certain range of number, but when you get to the top or bottom you don't want to just stop. You want to loop up to the bottom or top of the list respectively.

    Imagine a function where you are looping through an array.

    Function increase Or Decrease(variable As Integer) As Void
        n = (n + variable) % (listString.maxIndex + 1)  
        Print listString[n]
    End Function
    

    The reason that it is n = (n + variable) % (listString.maxIndex + 1) is to allow for the max index to be accounted.

    Those are just a few of the things that I have had to use modulus for in my programming of not just desktop applications, but in robotics and simulation environments.

提交回复
热议问题