整数运算实现四舍五入
在进行除法运算时难免会遇到四舍五入的问题,如果使用整数运算可能误差较大,因为纯整数运算会把整数部分全舍去,如果使用浮点运算,则会增加运算量,特别是运算量比较大的算法中或在移动设备和移动设备这些资源比较紧张的应用上,这种开销是值得考虑的。下面代码就是使用整数运算实现四舍五入的一个例子
static void Main(string[] args){int a = 100, b = 199, c;const int repeat = 1000000;const int loops = 100;double totalA = 0;double totalB = 0;for (int n = 0; n < loops; ++n) {DateTime begin = DateTime.Now;for (int i = 0; i < repeat; ++i) {c = (b + (a >> 1)) / a;}DateTime end = DateTime.Now;totalA += (end - begin).TotalMilliseconds;begin = DateTime.Now;for (int i = 0; i < repeat; ++i) {c = (int)Math.Round((double)b / a);}end = DateTime.Now;totalB += (end - begin).TotalMilliseconds;}System.Console.WriteLine("Integer used (ms): " + totalA / loops);System.Console.WriteLine("Double used (ms): " + totalB / loops);Console.ReadKey();}
Integer used (ms): 9.67055Double used (ms): 21.071208