Home > Backend Development > C#.Net Tutorial > How to calculate several powers in C language

How to calculate several powers in C language

下次还敢
Release: 2024-04-13 21:09:49
Original
684 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template