How to write exponential functions in C language, specific code examples are required
Overview:
Exponential functions are a common type of function in mathematics, which can represent is f(x) = a^x, where a is the base, x is the exponent, and f(x) is the function value. In C language, we can use loops and cumulative multiplication methods to implement the calculation of exponential functions. This article will introduce how to write a simple exponential function and give specific code examples.
Steps:
Define the base and exponent variables of the exponential function, as well as a variable for the cumulative result.
#includedouble power(double base, int exponent) { double result = 1.0; int i;
Determine the positive and negative conditions of the index, and choose different cumulative multiplication methods according to the positive and negative conditions of the index. If the exponent is a positive number, use a loop to accumulate the base; if the exponent is a negative number, first take the reciprocal of the base and then use a loop to accumulate.
if (exponent >= 0) { for (i = 0; i < exponent; i++) { result *= base; } } else { exponent = -exponent; for (i = 0; i < exponent; i++) { result *= 1 / base; } }
Return the cumulative result.
return result; }
Call the exponential function in the main function and output the result.
int main() { double base; int exponent; printf("请输入底数:"); scanf("%lf", &base); printf("请输入指数:"); scanf("%d", &exponent); printf("计算结果:%lf ", power(base, exponent)); return 0; }
Code example:
#includedouble power(double base, int exponent) { double result = 1.0; int i; if (exponent >= 0) { for (i = 0; i < exponent; i++) { result *= base; } } else { exponent = -exponent; for (i = 0; i < exponent; i++) { result *= 1 / base; } } return result; } int main() { double base; int exponent; printf("请输入底数:"); scanf("%lf", &base); printf("请输入指数:"); scanf("%d", &exponent); printf("计算结果:%lf ", power(base, exponent)); return 0; }
Summary:
This article introduces how to write a simple exponential function in C language, by using loops and cumulative multiplication way, we can calculate the corresponding exponential function value based on the given base and exponent. In the code example, we get the base and exponent from user input and output the calculated result. I hope this article will be helpful to readers who are new to C language.
The above is the detailed content of Writing a power function in C language. For more information, please follow other related articles on the PHP Chinese website!