使用规则仅使用数学函数向上/向下舍入?

时间:2011-06-04 04:21:59

标签: c# .net math

有些数学人请求帮助,我想只使用数学进行转换。功能。 (Pow,Floor ......等)只有单一陈述,不使用if else来检查1-4或6-9小数后的第5个数字。

  • 我希望将小数点后的5位数转换为小数点后的5位数,并遵循以下规则,最后是5和0。

规则1:

double number1 = 1.2345* 
if( * from 1 to 4)
   number1 ==> 1.23455 
if ( * from 6 to 9)
  number1  ==> 1.23460 

规则2:

double number2 = 1.2345* 
if( * from 1 to 4)
   number2 ==> 1.23450 

if ( * from 6 to 9)
  number2  ==> 1.23455 

我想出了规则1的答案,但它需要2个声明,我想知道是否可以只用1个声明来完成

number1 = Math.Floor((number1 + 0.00005) * 20000) / 20000 - 0.00005;
number1 = Math.Floor((number1 + 0.00005) * 20000) / 20000 ;

由于

2 个答案:

答案 0 :(得分:3)

对于规则#1:

var y = (int)((x - 0.00001) * 20000) / 20000.0 + 0.00005;

结果:

1.23450 => 1.23450
1.23451 => 1.23455
1.23452 => 1.23455
1.23453 => 1.23455
1.23454 => 1.23455
1.23455 => 1.23455
1.23456 => 1.23460
1.23457 => 1.23460
1.23458 => 1.23460
1.23459 => 1.23460
1.23460 => 1.23460

对于规则#2:

var y = (int)(x * 20000) / 20000.0;

结果:

1.23450 => 1.23450
1.23451 => 1.23450
1.23452 => 1.23450
1.23453 => 1.23450
1.23454 => 1.23450
1.23455 => 1.23455
1.23456 => 1.23455
1.23457 => 1.23455
1.23458 => 1.23455
1.23459 => 1.23455

答案 1 :(得分:2)

记住你如何舍入(到整数):

round (a) = floor (a + .5)

所以,现在把它加权一次,加权10,有些加上.5并加胡椒,除以10的幂除以你就定了。