c++ - 从文件中读取数字到两位有效数字?

标签 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;
    }

}

篮子.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/

相关文章:

c++ - 在 C++ 中定义类型转换运算符模板的正确方法是什么

c++ - Eigen C++ : Performance of sparse-matrix manipulations

c++ - 具有许多类的程序中的依赖倒置 (C++)

c++ - 类声明错误

c++ - C++ 中的嵌套 For 循环三角形

c++ - 如何使用 OpenCV 显示 PGM 图像

c++ - 返回结构体 char* 的问题

c++ - 使用 GCM(Galois 计数器模式)进行 AES 加密的 OpenSSL API

c++ - qt 错误 : undefined reference to `vtable for Thread'

c++ - 可以在DriverKit驱动程序中使用 `new`和 `delete`吗?