C语言计算数字幂的程序

要理解这个示例,您应该了解以下 C 编程 主题


下面的程序从用户那里获取两个整数(基数和指数),并计算幂。

例如:在 23 的情况下

  • 2 是基数
  • 3 是指数
  • 并且,幂等于 2*2*2

使用 while 循环计算数字的幂

#include <stdio.h>
int main() {
    int base, exp;
    long double result = 1.0;
    printf("Enter a base number: ");
    scanf("%d", &base);
    printf("Enter an exponent: ");
    scanf("%d", &exp);

    while (exp != 0) {
        result *= base;
        --exp;
    }
    printf("Answer = %.0Lf", result);
    return 0;
}

输出

Enter a base number: 3
Enter an exponent: 4
Answer = 81

我们也可以使用 pow() 函数来计算数字的幂。


使用 pow() 函数计算幂

#include <math.h>
#include <stdio.h>

int main() {
    double base, exp, result;
    printf("Enter a base number: ");
    scanf("%lf", &base);
    printf("Enter an exponent: ");
    scanf("%lf", &exp);

    // calculates the power
    result = pow(base, exp);

    printf("%.1lf^%.1lf = %.2lf", base, exp, result);
    return 0;
}

输出

Enter a base number: 2.3
Enter an exponent: 4.5
2.3^4.5 = 42.44

上面的程序只能在指数为正数时计算基数的幂。对于负指数,请使用以下数学逻辑

base(-exponent) = 1 / (baseexponent)

For example,

2-3 = 1 / (23)

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数来计算数字的幂。

  • 例如,输入 base = 2exponent = 3,返回值应为 **8**。
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战