[C] pow of library function

  The pow function implemented in this article is declared as

double MyPow(double m, int n);

  Next, two ways to implement the pow function are introduced:

1. Recursion

  Taking 2^3 as an example, assuming that 2^3 is difficult to obtain, then 2^3 can be converted into 2*2^2, so that only 2^2 needs to be calculated first. Similarly, 2^2 can be converted into 2 *2^1, and 2^1 can also be converted to 2*2^0. If the power is negative, it can be converted to a positive number to solve. (ps: 2^3 here means 2 to the third power, not bitwise XOR)

/*
* Function name: MyPow
*
* Function: Calculate the nth power of m (recursion)
*
* Entry parameters: m, n
*
* Exit parameter: 1.0 or m * MyPow(m, n - 1) or 1.0 / MyPow(m, -n)
*
* Return type: double
*/

double MyPow(double m, int n)
{
	if (0 == n)
	{
		return 1.0;
	}
	else if (n > 0)
		{
			return m * MyPow(m, n - 1);
		}
		else
		{
			return 1.0 / MyPow(m, -n);
		}
}

2. Iteration

  The self-decrement of the power is used as the loop condition. It should be noted here that when the power is negative, the power needs to be converted to its opposite number first.

/*
* Function name: MyPow
*
* Function: Calculate m to the nth power (iteration)
*
* Entry parameters: m, n
*
* Export parameter: ret
*
* Return type: double
*/

double MyPow(double m, int n)
{
	double ret = 1.0;

	if (0 == n)
	{
		;
	}
	else if (n > 0)
		{
			while (n--)
			{
				ret * = m;
			}
		}
		else
		{
			int k = -n;

			while (k--)
			{
				ret / = m;
			}
		}
	
	return ret;
}

3. Main function

#define _CRT_SECURE_NO_WARNINGS 1

/*
* Copyright (c) 2018, code farmer from sust
* All rights reserved.
*
* File name: MyPow.c
* Function: find the nth power of m
*
* Current version: V1.0
* Author: sustzc
* Completion date: April 15, 2018 10:33:46
*/

# include <stdio.h>
# include <assert.h>

# define EXP 0.000000000001

int main(void)
{
	double num1 = 0;
	int num2 = 0;
	double ret = 0.0;

	printf("Please enter two numbers:\n");
	assert(2 == scanf("%lf%d", &num1, &num2));

	if ((num1 < EXP) && (num1 > -EXP) && (0 == num2))
	{
		printf("Incorrect input! The value is meaningless!\n");
	}
	else
	{
		ret = MyPow (num1, num2);
		printf("%d power of %lf is %lf\n", num1, num2, ret);
	}

	return 0;
}

4. Output results







Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325388670&siteId=291194637