-8
class Solution
{

    static void Main(String[] args) 
    {
        int q = Convert.ToInt32(Console.ReadLine());
        for(int a0 = 0; a0 < q; a0++)
        {
            string[] tokens_x = Console.ReadLine().Split(' ');
            int x = Convert.ToInt32(tokens_x[0]);
            int y = Convert.ToInt32(tokens_x[1]);
            int z = Convert.ToInt32(tokens_x[2]);
             if(abs(z-x) > abs(z-y))
             {
         Console.WriteLine("Cat B\n");
        }
        else if(**

    abs(z-x) < abs(z-y))
            {

**
            Console.WriteLine("Cat A\n");
        }
        else 
        {
            Console.WriteLine("Mouse C\n");
        }

        }

How can I get the absolute value of a number in C#?

1
  • 5
    Why not try google first instead of asking here??
    – TaW
    Commented Jul 2, 2017 at 11:35

4 Answers 4

4

Are you looking for Math.Abs?

...
else if (Math.Abs(z-x) < Math.Abs(z-y))) {
  ... 
}

You can get rid of annoying Math. class prefix with a help of using static:

using static System.Math;

... 

else if (Abs(z-x) < Abs(z-y))) {
  ... 
}
2

Math.Abs

The Math static class contains many math operations.

1

As other answerers already pointed out, you are probably searching for Math.Abs. Example from the docs:

using System;

public class Example
{
   public static void Main()
   {
      decimal[] decimals = { Decimal.MaxValue, 12.45M, 0M, -19.69M, 
                             Decimal.MinValue };
      foreach (decimal value in decimals)
         Console.WriteLine("Abs({0}) = {1}", value, Math.Abs(value));

   }
}
// The example displays the following output:
//       Abs(79228162514264337593543950335) = 79228162514264337593543950335
//       Abs(12.45) = 12.45
//       Abs(0) = 0
//       Abs(-19.69) = 19.69
//       Abs(-79228162514264337593543950335) = 79228162514264337593543950335

However, since you did not know about this and did not find it either, you could have solved this yourself without great problems, like:

public static decimal Absolute(decimal value) {
    return (value < 0) ? -value : value;
}
0

Use the function System.Math.Abs. Math is a static class. The usual way of doing it was:

using System;

// ...

int result = Math.Abs(z - x);
Console.WriteLine(result);

Since C#6.0 you have the additional possibility of using static

using System;
using static System.Math;
using static System.Console;

// ...

int result = Abs(z - x);
WriteLine(result);

Explanation: The language C# does not by itself define an abs-function. However, there is a static class System.Math in the .NET class library which contains a lot of static math-functions. Among them the Abs function with overloads for different numeric types.

Not the answer you're looking for? Browse other questions tagged or ask your own question.