程序基本算法习题解析 编写一个计算幂级数的递归函数

思路:

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;
}

运行结果如下:

猜你喜欢

转载自blog.csdn.net/elma_tww/article/details/85018848