将变量输出到文本文件
问题描述:
我创建了一个运行Eulers方法的文件,我不知道如何获得计算出来的变量以显示在文本文件中。我想要显示y和x的每次迭代。我很抱歉,但我对C++很不熟悉,不知道为什么这不起作用。如果有人能帮助它,将会非常感激。将变量输出到文本文件
#include<iostream>
#include <math.h>
#include<fstream>
using namespace std;
int main()
{
double h = (1.0/100.0);
double y = 0;
double x = 0;
for (x = 0; x <= 1; x = x + h)
{
y = y + h*(x*exp(3 * x) - 2 * y);
ofstream demoFile;
demoFile.open("texttexttext.txt");
if (!demoFile) return 1;
demoFile << y << ' ' << x << endl;
}
demoFile.close();
return 0;
}
答
您遇到的问题是您每次迭代都会打开文件,导致您每次迭代都覆盖该文件。如果将文件移出for循环,您将获得正确的文本文件。
#include<iostream>
#include <math.h>
#include<fstream>
using namespace std;
int main()
{
double h = (1.0/100.0);
double y = 0;
double x = 0;
ofstream demoFile("texttexttext.txt"); // no need to call open just open with the constructor
if (!demoFile) return 1;
for (x = 0; x <= 1; x = x + h)
{
y = y + h*(x*exp(3 * x) - 2 * y);
demoFile << y << ' ' << x << endl;
}
return 0;
}
+0
Ahhhh问题解决了。非常感谢!! – George
究竟是什么不起作用?该文件没有创建? – Downvoter
您是否在包含操作系统的驱动器中运行此程序?有时在某些位置创建文件和文件夹可能需要特殊权限,因此程序将无法创建文件 – therainmaker