Menu Close

C语言练习:计算一个实数的n次方

C语言练习:计算一个整数的n次方. 计算一个数的幂

For example: In the case of 23

  • 2 is the base number
  • 3 is the exponent
  • And, the power is equal to 2*2*2

 

1. 利用while loop

#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

2. 利用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
READ  C语言练习:发现两个数的最大公约数(GCD)
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in C 决策和循环语句

Related Posts