Is it possible to check double and char data types

One interviewer asked me this question when I check his work, how can I check the type of char and double? Please explain me to me.

class Program
{
    static void Main(string[] args)
    {
        double d=0;

        if((double)d == 'c')
        {
            Console.WriteLine("working");
        }
        else 
        { 
            Console.WriteLine("not"); 
        }

        Console.ReadLine();
    }
}
+4
source share
3 answers

Char type is actually a 16-bit integer, so you can compare them if you want:

  Double left = 'B'; // <- 66.0
  Char right = 'A';  // <- it 16-bit int == 65 in fact 

  if (left > right) {...}

However, there is one problem: you should not use ==or !=without tolerance, as Doublewell as other types of floating point have a rounding error, therefore

  Double left = 66; 

maybe actually 66.000000000002or 65.9999999999998. Something like that:

  Double left = 'B'; // <- 66.0
  Char right = 'A';  // <- it 16-bit int == 65 in fact 

  // (left == right) comparison with tolerance
  // Since right is integer in fact, 0.1 tolerance is OK
  if (Math.Abs(left - right) < 0.1) {...} 
+8
source

GetType() typeof() .

class Program
{
    static void Main(string[] args)
    {
      double d=0;

      if(d.GetType() == typeof(Char))
      {
        Console.WriteLine("working");
      }
      else 
      { 
        Console.WriteLine("not"); 
      }

      Console.ReadLine();
   }
}
+2

, char , , char int16 16- , , double, integer long with it, ASCII . ...

double d = 65;
if (d == 'A')
{
    Console.WriteLine("working");
}
else { Console.WriteLine("not"); }

"", char "A" ASCII 65, 65, if.

0

Source: https://habr.com/ru/post/1532610/


All Articles