How to write x raised to the nth power in C language

下次还敢
Release: 2024-04-27 22:18:16
Original
1125 people have browsed it

In C language, there are two main ways to calculate x raised to the nth power: using the pow() function: The pow() function provides standard calculations, and its syntax is double pow(double x, int n); Use a loop: If the pow() function is not available, you can use a loop to calculate manually. The syntax is double pow(double x, int n) { ... }

How to write x raised to the nth power in C language

How to calculate x to the nth power in C language

In C language, there are two main methods to calculate x to the nth power:

Method 1: Use the pow() function

pow() The function is a standard function provided in the C math library and is used to calculate x raised to the nth power. The syntax is as follows:

<code class="c">double pow(double x, int n);</code>
Copy after login

where x is the base number and n is the exponent. pow() The function returns x raised to the n power.

Example:

<code class="c">#include <stdio.h>
#include <math.h>

int main() {
    double x = 2.5;
    int n = 3;

    double result = pow(x, n);

    printf("%f 的 %d 次方是 %f\n", x, n, result);

    return 0;
}</code>
Copy after login

Method 2: Using a loop

If not availablepow() function, you can also use a loop to manually calculate x raised to the nth power.

<code class="c">double pow(double x, int n) {
    double result = 1.0;

    for (int i = 0; i < n; i++) {
        result *= x;
    }

    return result;
}</code>
Copy after login

Example:

<code class="c">#include <stdio.h>

int main() {
    double x = 2.5;
    int n = 3;

    double result = pow(x, n);

    printf("%f 的 %d 次方是 %f\n", x, n, result);

    return 0;
}</code>
Copy after login

The above is the detailed content of How to write x raised to the nth power in C language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!