我需要得到三分之二并四舍五入到整数。
标准舍入:
AwayFromZero我相信这里是正确的选择。但是我认为我的乘法是不正确的,因为我得到的结果是0。
int totalPoints= 71625;
int twoThirds = (int)Math.Round((double)totalPoints * (2 / 3), 0, MidpointRounding.AwayFromZero);
答案应为47750。
答案 0 :(得分:2)
由于2/3
是int
的计算,因此它将返回0
,然后0 * totalPoints
等于0
我将使用2/3m
来使计算结果为十进制。这样您就可以得到期望的结果。
int totalPoints = 71625;
int twoThirds = (int)Math.Round(totalPoints * (2/3m), 0, MidpointRounding.AwayFromZero);
答案 1 :(得分:2)
尽管@ 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 :(得分:0)
(2/3),因为它在括号中。结果为0,因为这是整数除法。