文件SetPrecision C 代码

file setprecision c++ code

本文关键字:代码 SetPrecision 文件      更新时间:2023-10-16

我在C 中使用此代码很好,首先要求用户提供一个文件名,然后在该文件中保存一些数字。

但是我要做的是用两个小数点保存数字,例如用户类型2,我想保存数字2,但是有两个小数点位置 2.00

关于如何做的任何想法?

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
  double num;
  double data;
  string fileName = " ";
  cout << "File name: " << endl;
  getline(cin, fileName);
  cout << "How many numbers do you want to insert? ";
  cin >> num;
  for (int i = 1; i <= num; i++) {
    ofstream myfile;
    myfile.open(fileName.c_str(), ios::app);
    cout << "Num " << i << ": ";
    cin >> data;
    myfile << data << setprecision(3) << endl;
    myfile.close();
  }
  return 0;
}

好的,您需要在编写数据之前使用setprecision

我还将将文件的打开和关闭移出循环(当然是myfile的声明,因为通常是一个相当"沉重的"操作,可以在这样的循环中打开和关闭文件。<<<<<<<<<<<<<<<<<<<</p>

这是一个有效的演示:

#include <iostream>
#include <fstream>
#include <iomanip>
int main()
{
    std::ofstream f("a.txt", std::ios::app);
    double d = 3.1415926;
    f << "Test 1 " << std::setprecision(5) << d << std::endl;
    f << "Test 2 " << d << std::endl;
    f << std::setprecision(7);
    f << "Test 3 " << d << std::endl;
    f.precision(3); 
    f << "Test 3 " << d << std::endl;
    f.close();

}

但是请注意,如果您的号码为3.0,则您也需要std::fixed。例如。如果我们这样做:

    f << "Test 1 " << std::fixed << std::setprecision(5) << d << std::endl;

它将显示3.00000