面试题11—数值的整数次方

本文介绍了一个不使用库函数的手动实现幂运算的方法。通过递归和循环的方式计算一个数的任意次幂,并处理了特殊情况下(如0的0次方、0的负数次方)的异常情况。

题目:实现函数double Power(double num,int n),求num的n次方,不得使用库函数,不需要考虑大数问题。

代码示例:

#include<iostream>
using namespace std;
const double eps = 0.00000001;
long double Power(double num, int n)
{
	if (n > 0)
	{
		long double res = num;
		for (int i = 0; i < n-1; i++)
		res *= num;
		return res;
		//===略微优化一下乘方。
		/*long double tmp = Power(num, n >> 1);
		long double res = tmp*tmp;
		if ((n &0x01)==1)
			res *= num;
		return res;*/
	}
	else if (n == 0)
	{
		if (num > eps || num < -eps)
			return 1;
		else
			throw exception("0的0次方无意义!");
	}
	else
	{
		if (-eps < num&&num < eps)
			throw exception("0的负数次方无意义!");
		else
		{
			return 1.0/Power(num, -n);
		}
	}
}
void main()
{
	double num = 0;
	int n = 3;
	long double res = 0;
	cout << num << "的" << n << "次方为:";
	try{
		res = Power(num, n);
	}
	catch(exception &e)
	{
		cout << e.what() << endl;
	}
	cout << res << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值