C++詳解使用floor&ceil&round實現(xiàn)保留小數(shù)點后兩位
C++四舍五入保留小數(shù)點后兩位
示例
#include <iostream> using namespace std; int main() { double i = 2.235687; double j = round(i * 100) / 100; cout << "The original number is " << i << endl; cout << "The keep two decimal of 2.235687 is " << j << endl; system("pause"); return 0; }
運行結(jié)果
函數(shù)解析見下面
1、floor函數(shù)
功能:把一個小數(shù)向下取整 即就是如果數(shù)是2.2,那向下取整的結(jié)果就為2.000000
原型:double floor(doube x);
參數(shù)解釋:
x:是需要計算的數(shù)
示例
#include <iostream> using namespace std; int main() { double i = floor(2.2); double j = floor(-2.2); cout << "The floor of 2.2 is " << i << endl; cout << "The floor of -2.2 is " << j << endl; system("pause"); return 0; }
運行結(jié)果
2、ceil函數(shù)
功能:把一個小數(shù)向上取整
即就是如果數(shù)是2.2,那向下取整的結(jié)果就為3.000000
原型:double ceil(doube x);
參數(shù)解釋:
x:是需要計算的數(shù)
示例
#include <iostream> using namespace std; int main() { double i = ceil(2.2); double j = ceil(-2.2); cout << "The ceil of 2.2 is " << i << endl; cout << "The ceil of -2.2 is " << j << endl; system("pause"); return 0; }
運行結(jié)果
3、round函數(shù)
功能:把一個小數(shù)四舍五入 即就是如果數(shù)是2.2,那向下取整的結(jié)果就為2 如果數(shù)是2.5,那向上取整的結(jié)果就為3
原型:double round(doube x);
參數(shù)解釋:
x:是需要計算的數(shù)
示例
#include <iostream> using namespace std; int main() { double i = round(2.2); double x = round(2.7); double j = round(-2.2); double y = round(-2.7); cout << "The round of 2.2 is " << i << endl; cout << "The round of 2.7 is " << x << endl; cout << "The round of -2.2 is " << j << endl; cout << "The round of -2.7 is " << y << endl; system("pause"); return 0; }
運行結(jié)果
到此這篇關于C++詳解使用floor&ceil&round實現(xiàn)保留小數(shù)點后兩位的文章就介紹到這了,更多相關C++ floor ceil round內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C語言結(jié)構(gòu)體中內(nèi)存對齊的問題理解
內(nèi)存對齊”應該是編譯器的“管轄范圍”。編譯器為程序中的每個“數(shù)據(jù)單元”安排在適當?shù)奈恢蒙稀5荂語言的一個特點就是太靈活,太強大,它允許你干預“內(nèi)存對齊”。如果你想了解更加底層的秘密,“內(nèi)存對齊”對你就不應該再模糊了2022-02-02C++多字節(jié)字符與寬字節(jié)字符相互轉(zhuǎn)換
最近在C++編程中經(jīng)常遇到需要多字節(jié)字符與寬字節(jié)字符相互轉(zhuǎn)換的問題,自己寫了一個類來封裝wchar_t與char類型間的轉(zhuǎn)換2012-11-11關于C++讀入數(shù)字按位取出與進制轉(zhuǎn)換問題(典型問題)
這篇文章主要介紹了關于C++讀入數(shù)字按位取出與進制轉(zhuǎn)換問題,是一個非常典型的問題,本文通過實例舉例給大家介紹的非常詳細,需要的朋友可以參考下2020-02-02