Harry123

Hi ,

In c# I want to find the integer value of e.g. -5, how do I do this

For example 10-5 = 5 but 5-10 = -5, I just want to know what the difference is between the two numbers.

Thanks

harry



Re: Visual C# Language Difference between two numbers

ArranNyc

Math.Abs(i)



Re: Visual C# Language Difference between two numbers

mberseth

I think Math.Abs is what you are looking for. Here is a quick example ...

static void Main(string[] args)

{

Console.WriteLine(string.Format("Math.Abs(-5): {0}", Math.Abs(-5)));

Console.WriteLine(string.Format("Math.Abs(10 - 5): {0}", Math.Abs(10 - 5)));

Console.WriteLine(string.Format("Math.Abs(5 - 10): {0}", Math.Abs(5 - 10)));

}






Re: Visual C# Language Difference between two numbers

IsshouFuuraibou

-5 and 5 (any which way you come about them) have a sign difference. Math.Abs has nothing to do with why those two numbers are different (except to show you that they are both 5 away from 0)

in memory (binary, showing only 8-bits):
5 = 0000 0101
-5 = 1111 1011
At least in common negative number system.
5 != -5
but
Math.Abs(5) == Math.Abs(-5)

in terms of finding if a variable is "-5"

if ( i == -5 )
// i is -5

Also remember addition is commutative (can be performed either A+B or B+A) but subtraction is not ( A-B is not the same as B-A )

edit: spelling fix





Re: Visual C# Language Difference between two numbers

Peter Ritchie

In mathematics, the difference between two numbers is the subtraction of the two numbers. The difference between 5 and -5 is 0.

Maybe you can explain differently if that's not what you want.






Re: Visual C# Language Difference between two numbers

ArranNyc

The previous posts regarding mathematical difference are, of course, correct, but I think the OP was inferring that he was just looking to find a way to return a positive integer, regardless of the mathematical difference.

Sorry to be pedantic, but the difference between 5 and -5 is 10. (Diff between -5 and 5 is -10)





Re: Visual C# Language Difference between two numbers

patient

IsshouFuuraibou wrote:

Also remember addition is communicative (can be performed either A+B or B+A) but subtraction is not ( A-B is not the same as B-A )


Hi, i think you meant to say addition is commutative not communicative





Re: Visual C# Language Difference between two numbers

Matthew Watson

That's not pedantic. Smile




Re: Visual C# Language Difference between two numbers

Peter Ritchie

Yes, not pedantic: correct. 5 - -5 is 10, not zero.