How to calculate several powers in C language
Apr 13, 2024 pm 09:09 PMThere 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
#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; }
Use loops
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; }
Use recursion
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; }
Which method you choose depends on performance and code readability .
- pow() function is the fastest, but it requires an external library.
- The loop method is simple, but it is inefficient for large exponent.
- The recursive approach is elegant, but it can cause stack overflow.
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Usage of typedef struct in c language

How to implement the power function in C language

What to do if there is an error in scanf in C language
