C++ Ouput Exactly 2 Digits After Decimal Point 小数点后保留三位数字
生活随笔
收集整理的這篇文章主要介紹了
C++ Ouput Exactly 2 Digits After Decimal Point 小数点后保留三位数字
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
在C++編程中,有時(shí)候要求我們把數(shù)據(jù)保留小數(shù)點(diǎn)后幾位,或是保留多少位有效數(shù)字等等,那么就要用到setiosflags和setprecision函數(shù),記得要包含頭文件#include <iomanip>,請(qǐng)參考下面的示例:
?
#include <iostream> #include <iomanip> // Need this using namespace std;int main() {float a = 4, b = 3, c = 2;cout << a / b << endl;cout << b / c << endl;cout << setprecision(3) << a / b << endl;cout << setprecision(3) << b / c << endl;cout << setiosflags(ios::fixed) << setprecision(3) << a / b << endl;cout << setiosflags(ios::fixed) << setprecision(3) << b / c << endl;return 0; }?
輸出為:
1.33333 1.51.33 1.51.333 1.500?
如上面所示,默認(rèn)情況最多保留6位有效數(shù)字,我們?nèi)绻由蟬etprecision(3)的話,表明我們需要三位有效數(shù)字,如果我們想要小數(shù)點(diǎn)后三位有效數(shù)字,還需要在前面加上setiosflags(ios::fixed).
?
轉(zhuǎn)載于:https://www.cnblogs.com/grandyang/p/4846001.html
總結(jié)
以上是生活随笔為你收集整理的C++ Ouput Exactly 2 Digits After Decimal Point 小数点后保留三位数字的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【模式识别与机器学习】——3.9势函数法
- 下一篇: MQTT Client软件-MQTTBo