将Float转换为Long会给出负值

时间:2015-06-27 07:32:58

标签: c# floating-point type-conversion long-integer

为什么转换回来会给出-ve表达式?

"genres" => $Genres

输出:

float f = long.MaxValue;

Console.WriteLine("long to float: {0}",f);
Console.WriteLine("long Max: {0}",long.MaxValue);
Console.WriteLine("float to long casting: {0}",(long)f);
//Console.WriteLine("converting float to long: {0}",Convert.ToInt64(f));
//Above statement gives OverflowExection as expected.

同样,long to float: 9.223372E+18 long Max: 9223372036854775807 float to long casting: -9223372036854775808 会给出正确的结果。

1 个答案:

答案 0 :(得分:0)

正如M.kazem在评论中所建议的那样,它导致溢出,并且根据C#规范编译器默默地忽略它

Console.WriteLine("float to long casting: {0}",(long)f);

但是如果我们在check下转换为上面那么会抛出溢出表达式。

checked 
{
   Console.WriteLine("float to long casting: {0}",(long)f);
}