![](/img/trans.png)
[英]How can I quickly and accurately multiply a 64-bit integer by a 64-bit fraction in C#?
[英]Multiply an integer against a fraction with rounding to whole number in C#
我需要获得三分之二并四舍五入到整数。
标准舍入:
我相信AwayFromZero是在这里使用的正确选项。 但是我认为我的乘法是不正确的,因为我得到的结果是0。
int totalPoints= 71625;
int twoThirds = (int)Math.Round((double)totalPoints * (2 / 3), 0, MidpointRounding.AwayFromZero);
答案应该是47750。
因为2/3
是int
计算,所以它将返回0
,然后0 * totalPoints
等于0
我将使用2/3m
让计算结果为小数。 然后您可以获得您的期望结果。
int totalPoints = 71625;
int twoThirds = (int)Math.Round(totalPoints * (2/3m), 0, MidpointRounding.AwayFromZero);
虽然@ D-Shih答案在这里是正确的,但这并不是您可以获得的最佳答案。 即使对于小数,三分之二也不能精确表示,2 / 3m也不是三分之二,因此会产生舍入误差。 当您乘以数字时,您也乘以误差。 最好最后进行划分。 让我来说明一下区别:
int totalPoints = 71625;
decimal result1 = totalPoints * (2 / 3m); //47750.000000000000000000000002M
decimal result2 = (decimal)totalPoints * 2 / 3; //47750 (exactly)
double result3 = (double)totalPoints * 2 / 3; //47750 (exactly)
在这里没什么大不了的,因为结果是一样的。 但是如果我们稍微改变一下例子
double totalPointsDouble = 71626.5d;
decimal result1 = (decimal)totalPointsDouble * (1 / 3m); //23875.499999999999999999999998M
decimal result2 = (decimal)totalPointsDouble * 1 / 3m; //23875.5M
double result3 = totalPointsDouble * 1 / 3; //23875.5
int oneThird1 = (int)Math.Round((decimal)totalPointsDouble * (1 / 3m), 0, MidpointRounding.AwayFromZero);
//23875
int oneThird3 = (int)Math.Round(totalPointsDouble * 1 / 3, 0, MidpointRounding.AwayFromZero);
//23876
舍入误差传播到结果,并且结果不同。 根据数学计算,23876是正确的。
首先评估(2/3),因为它在括号中。 结果为0,因为这是整数除法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.