
从用户那里获取两个整数作为底数和指数,并按照下面的说明计算幂。
考虑以下内容以编写一个C程序。
按照下面给出的算法进行操作:
Step 1: Declare int and long variables. Step 2: Enter base value through console. Step 3: Enter exponent value through console. Step 4: While loop. Exponent !=0 i. Value *=base ii. –exponent Step 5: Print the result.
以下程序解释了如何用 C 语言计算给定数字的幂。
#include<stdio.h>
int main(){
int base, exponent;
long value = 1;
printf("Enter a base value:</p><p> ");
scanf("%d", &base);
printf("Enter an exponent value: ");
scanf("%d", &exponent);
while (exponent != 0){
value *= base;
--exponent;
}
printf("result = %ld", value);
return 0;
}当执行上述程序时,会产生以下结果 -
Run 1: Enter a base value: 5 Enter an exponent value: 4 result = 625 Run 2: Enter a base value: 8 Enter an exponent value: 3 result = 512
如果我们想要找到实数的幂,我们可以使用 pow 函数,它是 math.h 中的一个预定义函数。
#include<math.h>
#include<stdio.h>
int main() {
double base, exponent, value;
printf("Enter a base value: ");
scanf("%lf", &base);
printf("Enter an exponent value: ");
scanf("%lf", &exponent);
// calculates the power
value = pow(base, exponent);
printf("%.1lf^%.1lf = %.2lf", base, exponent, value);
return 0;
}当执行上述程序时,会产生以下结果 -
Enter a base value: 3.4 Enter an exponent value: 2.3 3.4^2.3 = 16.69
以上就是计算给定数字的幂的C程序的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号