English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

n!的c++程式怎麼寫阿.....有沒有會用遞迴和非遞迴去寫出來程式
感謝啦.....快要交了

2007-05-20 08:12:17 · 3 個解答 · 發問者 Anonymous in 電腦與網際網路 程式設計

3 個解答

遞迴:
#include
using namespace std;
long long fact(long long);
int main(int argc, char *argv[])
{
int num;
cin >> num;
cout << num <<"!=" << fact(num) << endl;
return EXIT_SUCCESS;
}
long long fact(long long n)
{
if (n==0 || n==1)
return 1;
else
return (n*fact(n-1));
}


另外一種(用迴圈):
#include
using namespace std;
long fact(long int);
int main(int argc, char *argv[])
{
int i,o;
long long n;
cin >> n;
o=n;
for(i=n-1;i>=1;i--)
{
n=n*i;
}
cout << o << "!=" << n;
return EXIT_SUCCESS;
}

2007-05-20 08:54:07 · answer #1 · answered by Chris 1 · 0 0

大部分的資料結構書上都會有這些範例
建議自己花時間找書參考...

2007-05-22 06:43:46 · answer #2 · answered by haha74sfnet 2 · 0 0

//Power by Visual Studio 2005
#include
#include
using namespace std;
unsigned int NON_RECURSIVE(unsigned int N)
{//非遞迴
unsigned int result=1,i;
for(i=1;i<=N;i++)
result*=i;
return result;
}
unsigned int RECURSIVE(unsigned int N)
{//遞迴
if(N==0)
return 1;
else
return N*RECURSIVE(N-1);
}
int main(int argc, char** argv)
{
//==========START==========//
int number;
cout<<"Input a number: ";
cin>>number;
cout<<"(1) "< cout<<"(2) "< //==========END==========//
system("PAUSE");
return EXIT_SUCCESS;
}

2007-05-20 09:10:46 · answer #3 · answered by Big_John-tw 7 · 0 0

fedest.com, questions and answers