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();
}
}
Run Code Online (Sandbox Code Playgroud)
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) {...}
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
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) {...}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |