1. 编程学习网 > 编程教程 > C语言教程 > C语言实例-计算一个数的 n 次方

C语言实例-计算一个数的 n 次方

C 语言实例

计算一个数的 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; }

本文由IT教学网整理发布,转载请注明出处:http://www.clang.cc//jiaocheng/cyuyan/1133.html

联系我们

在线咨询:点击这里给我发消息

咨询电话:400-998-2681

工作时间:7*24小时无休