Is there a module function of a number in C#?

Asked

Viewed 2,211 times

7

Example : module of -1 (|-1| = 1). I’ve done some research on the internet but all I think is the division module (%). I am trying to circumvent the common way of passing a negative number to a positive one, which would be to do a check to see if the number is negative or not before multiplying by -1.

  • 5

    Absolute value (abs): https://docs.microsoft.com/pt-br/dotnet/api/system.math.abs?view=netframework-4.8

  • I hadn’t remembered the abs method.

1 answer

11


For me module in programming has always been what this operator does, so the rest of the description is contradictory, but what you described seems to be that you want to take the value without signal, then it would be the method Abs(). As he takes the absolute value, that is, no sign, no matter if he is positive or negative his result will be a positive. This method exactly checks whether it is positive or not before changing the signal and makes the signal exchange (does not use nor if, or multiplication that are inefficient, can see the source code).

Math.Abs(-1) //resulta em 1

I put in the Github for future reference.

  • Thank you I didn’t remember the function of this function.

  • 1

    where is the Abs code for double? Or only for integers?

  • @jsbueno that I know is not available in C#, it is made by the standard C library of the operating system since it is more complex to do this and must have some trick, so preferred to delegate.

  • 3

    In fact the problem should be regional, maybe you have learned in school with the name absolute value, I learned how module same.. I only discovered that it is also called absolute value when I started programming. I also saw that it is called absolute value and also of module in Portugal.

  • I only discovered that Modulo can also be called Valor abosluto....agora. In English there is only "Absolute value" even.

  • @jsbueno you can use the static double Abs(double n) => n > 0 ? n : n * -1;.

  • In mathematics, in Brazilian Portuguese, we use "module", even. And the "module" in English, which exists in the programming languages is "rest".

  • As for my question, and I just wanted to see if there was something "ixperta" for floating point, and to confirm if you have this Integer API dispairty for Float. I don’t program in C#.

  • @jsbueno the API does not, but the implementation is quite different and even dependent on the platform, so the result may vary (although I don’t think it should).

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.