将“浮点”转换为“长”会得到负值

本文关键字:浮点 转换 | 更新日期: 2023-09-27 18:00:06

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

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

long.MinValue再次给出了正确的结果。

将“浮点”转换为“长”会得到负值

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

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

但是,如果我们在未检查的情况下转换上面的内容,那么就会抛出一个溢出表达式。

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