Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to check double and char data types

Tags:

c#

asp.net

One interviewer asked this question to me ,when I am checking it's working how it is possible to check type of char and double? Please any one explain me.

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

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

        Console.ReadLine();
    }
}
like image 883
stpdevi Avatar asked Dec 25 '22 11:12

stpdevi


1 Answers

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

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

  if (left > right) {...}

There's one issue, however: you should not use == or != without tolerance, since Double as well as other floating point types has round-up error, so

  Double left = 66; 

could be in fact 66.000000000002 or 65.9999999999998. Something like that:

  Double left = 'B'; // <- 66.0
  Char right = 'A';  // <- it's 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) {...} 
like image 167
Dmitry Bychenko Avatar answered Jan 05 '23 05:01

Dmitry Bychenko