我有這個代碼在C + +工作得很好,首先它要求用戶輸入 文件名,然後在該文件中保存一些數字。文件setprecision C++代碼
但是我試圖做的是有兩位小數,e.g的 用戶類型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;
}
爲什麼在寫入data之後使用'setprecision()'*? – nobar
@nobar:你可能應該回答這個問題,因爲這幾乎肯定是問題所在。 – PeterK
我不知道,只是試圖找到一種方法來做到這一點:/ – user3214262