Home  >  Article  >  Backend Development  >  How to calculate several powers in C language

How to calculate several powers in C language

下次还敢
下次还敢Original
2024-04-13 21:09:49624browse

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 calculate several powers in C language

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 .

  • 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn