从文件读取数字到两位有效数字?

时间:2012-11-21 06:52:48

标签: c++

#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;
    }

}

basket.txt

27.9933
18.992
9.754
11.2543

无论如何,我可以使数字只显示两位有效数字?另外,如果我想围绕一个数字,我该怎么做?例如,如果我有数字6.66和4.33,我想要6.66-> 6.70和4.33-> 4.30。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

尝试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

希望这就是你想要的。