Math.Floor VS投为整型在C#整型、Math、Floor、VS

2023-09-03 01:53:46 作者:羊入我口

是否有任何理由之一将preFER使用Math.Floor VS铸造为整型?

 双击NUM;
双楼= Math.Floor(NUM);
 

 双击NUM;
长楼=(长)民;
 

解决方案 Visual Studio 调试技巧之即时窗口的妙用

有一个整体式,并使用Math.Floor铸造之间的一些差异:

当铸造整数类型,你最终会得到一个整数类型(很明显)。所以,如果你想保持数为双,使用地板更容易。 作为1结果,铸件将不能正确如果给定的数目过大而被重新由给定积分型psented $ P $工作(一个双可以重新present大得多号码比长)。 在楼舍入到负无穷大。铸造轮趋于零。

Are there any reasons one would prefer to use Math.Floor vs casting to an integral type?

double num;
double floor = Math.Floor(num);

OR

double num;
long floor = (long)num;

解决方案

There are some differences between casting to an integral type and using Math.Floor:

When casting to an integral type, you'll end up with an integral type (obviously). So if you want to keep the number as a double, using Floor is easier. As a consequence of 1, casting will not work correctly if the given number is too large to be represented by the given integral type (a double can represent much larger numbers than a long). Floor rounds towards negative infinity. Casting rounds towards zero.