C 語言實例 - 計算一個數的 n 次方
計算一個數的 n 次方,例如: 23,其中 2 為基數,3 為指數。
實例 - 使用 while
#include <stdio.h>
int main()
{
    int base, exponent;
    long long result = 1;
    printf("基數: ");
    scanf("%d", &base);
    printf("指數: ");
    scanf("%d", &exponent);
    while (exponent != 0)
    {
        result *= base;
        --exponent;
    }
    printf("結果:%lld", result);
    return 0;
}
運行結果:
基數: 2 指數: 3 結果:8
實例 - 使用 pow() 函數
#include <stdio.h>
#include <math.h>
int main()
{
    double base, exponent, result;
    printf("基數: ");
    scanf("%lf", &base);
    printf("指數: ");
    scanf("%lf", &exponent);
    // 計算結果
    result = pow(base, exponent);
    printf("%.1lf^%.1lf = %.2lf", base, exponent, result);
    return 0;
}
運行結果:
基數: 2 指數: 3 2.0^3.0 = 8.00
實例 - 遞歸
#include <stdio.h>
int power(int n1, int n2);
int main()
{
    int base, powerRaised, result;
    printf("基數: ");
    scanf("%d",&base);
    printf("指數(正整數): ");
    scanf("%d",&powerRaised);
    result = power(base, powerRaised);
    printf("%d^%d = %d", base, powerRaised, result);
    return 0;
}
int power(int base, int powerRaised)
{
    if (powerRaised != 0)
        return (base*power(base, powerRaised-1));
    else
        return 1;
}

 C 語言實例