我想用这样的四舍五入找到一些Math
,如果它存在的方法:数学四舍五入方法
3219 to 3300
11380 to 11400
12583 to 12600
8275 to 8300
1778 to 1800
399 to 400
340 to 400
305 to 400
266 to 300
123 to 200
32 to 100
3 to 100
1 to 100
我想用这样的四舍五入找到一些Math
,如果它存在的方法:数学四舍五入方法
3219 to 3300
11380 to 11400
12583 to 12600
8275 to 8300
1778 to 1800
399 to 400
340 to 400
305 to 400
266 to 300
123 to 200
32 to 100
3 to 100
1 to 100
根据你的榜样,你要四舍五入到最接近的100,你可以这样做:
int x = 3219; // or any other input
int result = (x+99)/100*100;
这种算法的优点是,你留在整数世界。所以这意味着没有舍入错误(只要subresult可以表示为一个整数),我们很好。
可以概括这种方法,如:
哪里n
是你想要的号码围捕。
基于@wenston的回答,您可以构建一个branchfree算法患有整数溢出少:
public static int RoundUp(this int x, int n = 100) {
int r = x % n;
return x + (n - r) % n;
}
您可以将其作为扩展方法。 –
@KfirGuy:这是一个好主意。完成。 –
遭受整数溢出例如'2147483000!= RoundUp(2147482999,1000)' – weston
使用此:
var value = 1234;
var result = (int)(Math.Ceiling(value/100f)*100);
为了防止整数溢出问题与中间结果(例如RoundUp(2147482999, 1000)
)我们不应该在分割前加n
到x
:
public static int RoundUp(int x, int n) {
var r = x % n;
if (r == 0) return x;
return x + n - r;
}
x % n
是除法的其余部分。如果这不是零,我们需要添加这个(n - x % n
)的恭维,其范围为[1..n]
。当它是== n
,我们实际上希望它增加零,所以我们可以通过另一个% n
作为Willem pointed out来实现,这使得它无分支,但是具有两个mod而不是一个。
public static int RoundUp(int x, int n) {
return x + (n - x % n) % n;
}
而且,只是一个提醒,如果你真的关心超出了整数溢出,那么您可以在一个checked
块包装:
public static int RoundUp(int x, int n) {
checked
{
return x + (n - x % n) % n;
}
}
所以你要四舍五入到最接近的100? –
除以100,舍入,乘以100. –
除以100,加0.5,舍入,乘以100 –