There are three ways to calculate powers: using the pow() function (fastest, but requires an external library), using a loop (simple, but inefficient), and using recursion (elegant, but may cause stack overflow).
How to use C language to calculate power
Use the pow() function directly
<code class="c">#include <math.h> int main() { double base = 2.0; int exponent = 3; double result = pow(base, exponent); printf("(%f) ^ %d = %f\n", base, exponent, result); return 0; }</code>
Use loops
<code class="c">int main() { double base = 2.0; int exponent = 3; double result = 1.0; for (int i = 0; i < exponent; i++) { result *= base; } printf("(%f) ^ %d = %f\n", base, exponent, result); return 0; }</code>
Use recursion
<code class="c">double power(double base, int exponent) { if (exponent == 0) { return 1.0; } else if (exponent < 0) { return 1.0 / power(base, -exponent); } else { return base * power(base, exponent - 1); } } int main() { double base = 2.0; int exponent = 3; double result = power(base, exponent); printf("(%f) ^ %d = %f\n", base, exponent, result); return 0; }</code>
Which method you choose depends on performance and code readability .
The above is the detailed content of How to calculate several powers in C language. For more information, please follow other related articles on the PHP Chinese website!