#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream basketFile;
basketFile.open("basket.txt");
double price;
while (!basketFile.eof()) {
basketFile >> price;
cout << price << endl;
}
}
篮子.txt
27.9933
18.992
9.754
11.2543
无论如何,我可以让数字只显示两位有效数字吗?另外,如果我想将数字四舍五入,我该怎么做?例如,如果我有数字 6.66 和 4.33,我想要 6.66->6.70 和 4.33->4.30。有帮助吗?
最佳答案
尝试 setprecision
.
要对数字进行四舍五入,请参阅 round
.
此外,如果您决定四舍五入到 0.1 精度,我相信您可以在四舍五入的结果后附加零 0
。
#include <iostream>
#include <iomanip>
using namespace std;
void p(double x) {
cout << fixed << setprecision(1) << x << 0 << endl;
}
int main() {
p(27.9933);
p(18.992);
p(9.754);
p(11.2543);
p(6.66);
p(4.33);
return 0;
}
上面的代码输出:
28.00
19.00
9.80
11.30
6.70
4.30
希望这就是你想要的。
关于c++ - 从文件中读取数字到两位有效数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13487866/