1. 程式人生 > >程式基本演算法習題解析 編寫一個計算冪級數的遞迴函式

程式基本演算法習題解析 編寫一個計算冪級數的遞迴函式

思路:

x^{^{n}}=\left\{\begin{matrix} 1, & n=0\\ x\bullet x^{n-1},& n>0 \end{matrix}\right.

附上程式碼:

// Chapter6_1.cpp : Defines the entry point for the application.
// 編寫一個計算冪級數的遞迴函式

#include "stdafx.h"
#include<iostream>
using namespace std;
//求x的n次冪
int funPower(int x,int n)
{
	if(n==0)
		return 1;
	else
	{
		n = n-1;
		return x*funPower(x,n);
	}
}
int main()
{
	int x,n;
	cout << "input x,n: ";
	cin >> x >> n;
	int result;
	result = funPower(x,n);
	cout << x << "的" << n << "次方為:" << result << endl;
	system("pause");
	return 0;
}

執行結果如下: