Q) 撰寫一個定義和測驗階乘函式的程式。一個數的階乘是從 1 到 N 的所有整數的乘積。例如,5 的階乘是 1 * 2 * 3 * 4 * 5 = 120
問題:我可以列印結果,但不能像這樣列印:
let n = 5
Output : 1 * 2 * 3 * 4 * 5 = 120;
我的代碼:
# include <bits/stdc .h>
using namespace std;
int Factorial (int N)
{
int i = 0;int fact = 1;
while (i < N && N > 0) // Time Complexity O(N)
{
fact *= i;
}
return fact;
}
int main()
{
int n;cin >> n;
cout << Factorial(n) << endl;
return 0;
}
uj5u.com熱心網友回復:
我能夠列印結果,但不能像這樣列印:讓 n = 5 輸出:1 * 2 * 3 * 4 * 5 = 120;
這確實是您的代碼正在做的事情。您只列印結果。如果要在列印結果之前列印從 1 到 N 的每個整數,則需要更多 cout 呼叫或其他方式來操作輸出。
這應該只是一個想法,這遠不是一個很好的例子,但它應該可以完成這項作業。
int main()
{
int n;cin >> n;
std::cout << "Factorial of " << n << "!\n";
for (int i =1; i<=n; i )
{
if(i != n)
std::cout << i << " * ";
else
std::cout << n << " = ";
}
cout << Factorial(n) << endl;
return 0;
}
使用std::string和std::stringstream的更好方法
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cin >> n;
stringstream sStr;
sStr << "Factorial of " << n << " = ";
for (int i = 1; i <= n; i )
{
if (i != n)
sStr << i << " * ";
else
sStr << i << " = ";
}
sStr << Factorial(n) << endl;
cout << sStr.str();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450538.html
上一篇:獲取串列中的值的函式
