将 Float 转换为 Long 给出负值
Converting Float to Long gives negative value
为什么向后转换会给出 -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);
但是如果我们将上面的代码转换为 under checked 则会抛出一个溢出表达式。
checked
{
Console.WriteLine("float to long casting: {0}",(long)f);
}
为什么向后转换会给出 -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);
但是如果我们将上面的代码转换为 under checked 则会抛出一个溢出表达式。
checked
{
Console.WriteLine("float to long casting: {0}",(long)f);
}