阶乘-c++ 我想以不同的方式打印



我想打印一个数字的阶乘略有不同。我对 c++ 很陌生,所以我想在这里得到一些帮助。假设我给出输入为 5,这意味着如果逻辑正确,我将得到 120 作为我的输出。但是我想要的输出是这样的 1 2 6 24 120

就像第一个f * i然后再次f *我喜欢那样。我对逻辑有点困惑,所以请有人帮助我。

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream fact("factorial.txt");
int i,n,f=1;
cin>>n;
for(i=1;i<=n;i++)
{
f=f*i;
fact<<i<<" ";
}
fact<<endl;
fact<<f<<" ";
return 0 ;
}

在循环中添加f就可以了;我还添加了更多文本

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
cout << "Please Enter a Number for calculation: ";
ofstream fact("factorial.txt");
int i,n,f=1;
cin>>n;
for(i=1;i<=n;i++)
{
f=f*i;
fact<<f<<" ";
}
fact<<endl;
fact<<f<<" ";
cout << "The result is:" << f;
cout << "nYou can check the process in the Factorial.txt";
return 0 ;
}

你也可以考虑看看这篇文章;因为它会在将来使用C++时帮助你。 为什么"使用命名空间 std"是一种不好的做法。

最新更新