我有一个C ++代码,我希望将输出打印在文本文件中。输出一次打印一个,这意味着当我打开文本文件时有一个输出,而当我关闭并重新打开它时将有另一个输出。我该如何做,以便每次打印输出时,所有内容都打印出来并保留在文本文件中,这样我就可以在文本文件中看到所有结果了。
#include <iostream>
#include "math.h"
#include <stdio.h>
using namespace std;
float p(int N, int k, float R);
int main ()
{
float R=0.158; float N=65;
float mean = 0.0; float ps=0.0;
for (int k=1; k<=N; k++)
{
float prob=p(N,k,R); ps = ps+prob;
mean = mean + k*prob;
freopen ("output.txt","w",stdout);
cout << k << " " << p(N,k,R) << endl;
}
cout << "ps: " << ps << " mean: " << mean << endl;
}
float p(int N, int k, float R)
{
if (k==1)
{
return pow(R,N-1);
}
else if (N==k)
{
return pow(1-R,(k*(k-1))/2);
}
else
{
return p(N-1,k,R)*(1-pow(1-R,k))+p(N-1,k-1,R)*pow(1-R,k-1);
}
}
答案 0 :(得分:0)
通过查看有关此威胁的所有反馈,我已经获得了将代码输出到文本文件中的代码,如下面的代码所示。
#include <iostream>
#include "math.h"
#include <stdio.h>
using namespace std;
float p(int N, int k, float R);
int main ()
{
freopen ("output.txt","w",stdout);
float R=0.158; float N=65;
float mean = 0.0; float ps=0.0;
for (int k=1; k<=N; k++)
{
float prob=p(N,k,R); ps = ps+prob;
mean = mean + k*prob;
cout << k << " " << p(N,k,R) << endl;
}
cout << "ps: " << ps << " mean: " << mean << endl;
fclose (stdout);
return 0;
}
float p(int N, int k, float R)
{
if (k==1)
{
return pow(R,N-1);
}
else if (N==k)
{
return pow(1-R,(k*(k-1))/2);
}
else
{
return p(N-1,k,R)*(1-pow(1-R,k))+p(N-1,k-1,R)*pow(1-R,k-1);
}
}