【C语言】求数值的正数次方

//数值的正数次方
//实现函数double power(double base, int exponent),求base的exponent次方,不得使用库函数,不需要考虑大数问题。
//注意:考虑非法输入的返回。
#include 
#include 
bool Inpot_illegal = false;
bool equal(double num1, double num2)   //判断两数是否相等
{
	if ((num1 - num2) > -0.00001 && (num1 - num2) < 0.00001)
		return true;
	else
		return false;
}
double PowerExp(double base, int exponent)  //当指数>=0时,底数也>=0时计算
{
	if (exponent == 0)
		return 1;
	if (exponent == 1)
		return base;

	double result = PowerExp(base, exponent >> 1);
	result *= result;

	if (exponent & 0x1 == 1)
		result *= base;

	return result;
}
double Power(double base, int exponent)    //所有情况的求解
{
	Inpot_illegal = false;

	if (equal(base, 0.0) && exponent <= 0) //0的0次方及0的负数次方都是非法输入 
	{
		Inpot_illegal = true;
		return 0.0;
	}
	int absExponent;   //取指数绝对值
	if (exponent < 0)
		absExponent = abs(exponent);
	else
		absExponent = exponent;

	double result = PowerExp(base, absExponent); //正常求解

	if (exponent < 0)   //指数小于0,则取倒数
		result = 1.0 / result;
	return result;
}
int main()
{
	int exp;
	double base, res;
	printf("请依次输入底数和指数:");
	scanf_s("%lf %d", &base, &exp);
	res = Power(base, exp);

	if (Inpot_illegal)	//如果非法输入,输出error  
	{
		printf("error\n");
		return 0;
	}
	else
		printf("结果为:%f\n", res);
	return 0;
}

你可能感兴趣的:(【C语言】求数值的正数次方)