文件SetPrecision C 代码
file setprecision c++ code
我在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
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 文件SetPrecision C 代码