如何乘以两倍的长整数

问题描述 投票:2回答:3

很抱歉问这样一个初学者的问题,但我想不出来。

我有一个长整数,我想除以1.28,然后将其向上或向下舍入为最接近的整数。

long size = 24524343254;
double ratio = 1.28;
size = size * 1.28; //Error Cannot implicitly convert type 'double' to 'long'
c# double rounding long-integer multiplication
3个回答
6
投票

您需要显式地将双精度结果强制转换回long(因为编译器指出-没有隐式转换):

size = (long)Math.Round(size * 1.28);

如果要四舍五入到最接近值,则需要Math.Round(在特殊情况下,要四舍五入的数字位于两个数字之间的中间,那么默认情况下会四舍五入到最接近的数字)。如果您只想四舍五入,也可以简单地将结果转换回(long)(size * 1.28)

如@CodeInChaos所指出,从long到double的隐式转换(size * 1.28将把size首先转换为double)可能会导致精度损失为doubles only have a precision of 53 bits,但long为64位。


2
投票

您应该持续投放结果。

size = (long)Math.Round(size * 1.28);

2
投票

您也可以考虑使用decimal

size = (long)Math.Round(size * 1.28m);//note the m making the literal a decimal.

在这种情况下,与double相比,这有两个优点:

  • [decimal可以精确表示每个long值(与double仅具有53个尾数位,十进制具有> 90个尾数位,足以表示[​​C0]使用的63位)]
  • 它可以精确表示1.28。

[您还应确保long对您来说还不错。将MidpointRounding.ToEven舍入为1.5,但是将2舍入为0.5

使用0强制转换为Decimal时,如果该值超出long的范围,则会导致异常。

[使用long时,溢出行为取决于模式。如果在double部分中,它将引发异常,在checked上下文中将导致未定义的值。由于很少需要未定义的值,因此我建议将uncheckedchecked结合使用:

double
© www.soinside.com 2019 - 2024. All rights reserved.