如何将Math.Ceiling结果转换为int?
Math.Ceiling
返回double
因为double
可以存储更大的数字。 但是,如果我确定int
类型能够存储结果我应该如何转换? Cast (int) Math.Ceiling(...
? (int) Math.Ceiling(...
是否安全?
如果你确定你没有超过int的容量,那么它应该是完全安全的
int myInt = (int)Math.Ceiling(...);
如果你不确定绑定,你可以使用long
而不是int
。
从C ++实践中,我将使用以下内容。 即使天花板返回99.99999 … 8或100.000000 … 1,也能保证获得正确的结果
var result = (int)(Math.Ceiling(value) + 0.5);
如果您信任它的实现,下面的代码也应该工作
var result = Convert.ToInt32(value);
我会去的
int x = (int)Math.Ceiling(0.9); // 1
如果你不确定你总是可以放一个if语句并检查你得到的数字是否更高然后是int.MaxValue
int oInt = Convert.ToInt32(Math.Ceiling(value));
由于Math.Ceiling
返回double
并且您想将其转换为int
,因此请使用Convert
Class。
例:
double[] values= { Double.MinValue, -1.38e10, -1023.299, -12.98, 0, 9.113e-16, 103.919, 17834.191, Double.MaxValue }; int result; foreach (double value in values) { try { result = Convert.ToInt32(value); Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", value.GetType().Name, value, result.GetType().Name, result); } catch (OverflowException) { Console.WriteLine("{0} is outside the range of the Int32 type.", value); } } // -1.79769313486232E+308 is outside the range of the Int32 type. // -13800000000 is outside the range of the Int16 type. // Converted the Double value '-1023.299' to the Int32 value -1023. // Converted the Double value '-12.98' to the Int32 value -13. // Converted the Double value '0' to the Int32 value 0. // Converted the Double value '9.113E-16' to the Int32 value 0. // Converted the Double value '103.919' to the Int32 value 104. // Converted the Double value '17834.191' to the Int32 value 17834. // 1.79769313486232E+308 is outside the range of the Int32 type.