C++ 多种取整函数的使用和区别: ceil() floor() round() trunc() rint() nearbyint()
取整函數:
ceil()?????右向取整:數軸上右邊最靠近的整數,向大的方向取值;ceil “天花板”
floor()???左向取整:數軸上左邊最靠近的整數,向小的方向取值;floor “地板”
round() 接近取整:不管正負,即四舍五入后留下整數部分??round(x) = floor(x+0.5)
trunc()??零向取整:不管正負,直接舍掉小數部分只留下整數部分,向原點0的方向取值
rint() nearbyint():四種方法任選其一,由?fesetround()?配合設置,見例程二說明
例程一:ceil() floor() round() trunc()用法
#include <iostream> #include <cmath>using namespace std;int main() {double num[4] = {13.6, 3.23, -13.6, -3.23};for (auto n:num){cout<< " ceil(x) floor(x) round(x) trunc(x):x = " << n << endl;cout<< "\t" << ceil(n) << "\t" << floor(n) << "\t"<< round(n) << "\t" << trunc(n) << endl << endl;}return 0; }/*ceil(x) floor(x) round(x) trunc(x):x = 13.614 13 14 13ceil(x) floor(x) round(x) trunc(x):x = 3.234 3 3 3ceil(x) floor(x) round(x) trunc(x):x = -13.6-13 -14 -14 -13ceil(x) floor(x) round(x) trunc(x):x = -3.23-3 -4 -3 -3-------------------------------- Process exited after 0.6186 seconds with return value 0 請按任意鍵繼續. . . */例程二:fegetround() fesetround()用法
函數原型:
int fesetround(int mode); 設置取整模式
int fegetround(void); 獲取當前取整模式
mode 值:
Round to nearest value ? FE_TONEAREST? ? ?== 0
Round downward? ? ? ? ? ? FE_DOWNWARD? ? ?== 1024
Round upward? ? ? ? ? ? ? ? ?FE_UPWARD? ? ? ? ? ?== 2048
Round towards zero? ? ? ? FE_TOWARDZERO ?== 3072
default value:? ? ? ? ? ? ?? ?FE_TONEAREST? ? ? == 0
例程三:nearbyint() rint()用法
#include <iostream> #include <array> #include <cmath> #include <cfenv> using namespace std;int main(void) {array<double,4> num={13.6, 3.23, -13.6, -3.23};array<string,6> str={"nearbyint(x), x = \n", "\nmode = ","FE_TONEAREST(default) = ","FE_DOWNWARD = ","FE_UPWARD = ","FE_TOWARDZERO = " };cout<<str.at(0);for (auto n:num) cout<<"\t"<<n; cout<<endl;for (int i=0;i<4;i++){fesetround(i*1024);cout<<str.at(1)<<str.at(i+2)<<fegetround()<<endl;for (auto n:num) cout<<"\t"<<nearbyint(n); cout<<endl;}return 0; }/* nearbyint(x), x =13.6 3.23 -13.6 -3.23mode = FE_TONEAREST(default) = 014 3 -14 -3mode = FE_DOWNWARD = 102413 3 -14 -4mode = FE_UPWARD = 204814 4 -13 -3mode = FE_TOWARDZERO = 307213 3 -13 -3-------------------------------- Process exited after 0.6 seconds with return value 0 請按任意鍵繼續. . . */?
總結
以上是生活随笔為你收集整理的C++ 多种取整函数的使用和区别: ceil() floor() round() trunc() rint() nearbyint()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: perf常用用法简介
- 下一篇: URL重写实现会话跟踪