C++ Ouput Exactly 2 Digits After Decimal Point 小数点后保留三位数字
生活随笔
收集整理的這篇文章主要介紹了
C++ Ouput Exactly 2 Digits After Decimal Point 小数点后保留三位数字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
在C++編程中,有時候要求我們把數據保留小數點后幾位,或是保留多少位有效數字等等,那么就要用到setiosflags和setprecision函數,記得要包含頭文件#include <iomanip>,請參考下面的示例:
?
#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?
如上面所示,默認情況最多保留6位有效數字,我們如果加上setprecision(3)的話,表明我們需要三位有效數字,如果我們想要小數點后三位有效數字,還需要在前面加上setiosflags(ios::fixed).
?
轉載于:https://www.cnblogs.com/grandyang/p/4846001.html
總結
以上是生活随笔為你收集整理的C++ Ouput Exactly 2 Digits After Decimal Point 小数点后保留三位数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【模式识别与机器学习】——3.9势函数法
- 下一篇: MQTT Client软件-MQTTBo