其實c++自身是沒有四舍五入函數round()的,若果你要用到的話,可以自己寫一個round(),不過要用到floor()和ceil這兩個函數如下:
1 #include<iostream> 2 #include<cmath> 3 using namespace std; 4 5 double round(double x) 6 { 7 return (x>0.0)? floor(x+0.5):ceil(x-0.5); 8 } 9 int main() 10 { 11 cout<<round(0.4)<<" "<<round(1.2)<<" "<<round(2.7)<<"\n"; 12 cout<<round(-5.4)<<" "<<round(-1.2)<<" "<<round(-2.7)<<"\n"; 13 return 0; 14 }
測試結果如下: