软件编程
位置:首页>> 软件编程>> C#编程>> C#使用round函数四舍五入的方法

C#使用round函数四舍五入的方法

作者:niuniu  发布时间:2022-01-19 04:33:57 

标签:C#,round,函数,四舍五入

本文实例讲述了C#使用round函数四舍五入的方法。分享给大家供大家参考。具体分析如下:

C#中的round函数实际上不是真正的四舍五入函数,一般的程序设计语言的round函数也都不是四舍五入函数,而是银行家舍入法函数,也就是“四舍六入五考虑,五后非零就进一,五后为零看奇偶,五前为偶应舍去,五前为奇要进一”

但C#中的round函数似乎也没有完全遵循这个规则,我们来看看微软官方给的范例:


using System;
public class Example
{
 public static void Main()
 {
  double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
  foreach (double value in values)
    Console.WriteLine("{0} --> {1}", value,
 Math.Round(value, 2, MidpointRounding.AwayFromZero));
 }
}
// The example displays the following output:
//    2.125 --> 2.13
//    2.135 --> 2.13
//    2.145 --> 2.15
//    3.125 --> 3.13
//    3.135 --> 3.14
//    3.145 --> 3.15

看到了吧,2.135和3.135 做了round操作后得到的结果居然是2.135不进位,2.145进位了。

希望本文所述对大家的C#程序设计有所帮助。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com