当前位置:网站首页>C Primer Plus Chapter 9 question 9 POW function

C Primer Plus Chapter 9 question 9 POW function

2022-07-05 23:00:00 multydoffer

simulation <math.h> Medium pow Function to write a power function , Return to one double Positive integer power of type number . Improve the function , So that it can correctly calculate the negative power . in addition , Function to handle 0 Any power of is 0, Any number of 0 The power is 1( Function should warn 0 Of 0 Power undefined , Therefore, the value is treated as 1). To use recursive functions , And test the function in the program .

Here is the code :

#include <stdio.h>

double power(double x, int n);

int main(void)
{
	double x;
	int n;
	
	printf("Enter a number:");
	scanf("%lf", &x);
	printf("Enter a integer:");
	scanf("%d", &n);
	printf("%.2lf^%d = %lf", x, n, power(x, n));
	return 0;
}

double power(double x, int n)
{
	double pow = x;
	if(!x)
	{
		if(!n) //0 Of 0 Power  
		{
		    printf("For there is no definition for 0^0, so I return 1.\n");
		    return 1.0;
		}
		else
		return 0.0;
	}
	if(n > 1)
		pow *= power(x, n-1);
	else if(!n)
	return 1.0;
	else if(n == 1) // Recursive termination  
	return pow;
	else if(n < 0)
	return 1.0 / pow / power(x, -n-1);	
}

原网站

版权声明
本文为[multydoffer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140348340655.html