四捨五入的問題
我們很常利用的Rounding函數會是這樣的
inline int Round(double val){ return (int)(val+0.5);}
不過四捨五入在負數上的運作會有點不同,下面的程式就是展示這個不同點,
就wiki上的定義 http://en.wikipedia.org/wiki/Rounding
和我們慣用的寫法在負數會有些不同,
和將負數位移成正數之後,再位移回負數的寫法,
以及+0.5之後取floor的寫法是相同的結果。
#include <iostream>#include <cmath>#include <cstdlib>using namespace std;int main(){ cout << "Rounding in negtive value:" << endl; cout << (int)(-0.4 + 0.5) << endl; cout << (int)(-0.5 + 0.5) << endl; cout << (int)(-1.4 + 0.5) << endl; cout << (int)(-1.5 + 0.5) << endl; cout << "Rounding in negtive value(shift&shift back):" << endl; cout << (int)(-0.4 + 128 + 0.5) -128 << endl; cout << (int)(-0.5 + 128 + 0.5) -128 << endl; cout << (int)(-1.4 + 128 + 0.5) -128 << endl; cout << (int)(-1.5 + 128 + 0.5) -128 << endl; cout << "Rounding in negtive value(+0.5&floor):" << endl; cout << floor(-0.4 + 0.5) << endl; cout << floor(-0.5 + 0.5) << endl; cout << floor(-1.4 + 0.5) << endl; cout << floor(-1.5 + 0.5) << endl; system("pause"); return 0;}
留言