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

C 语言教程 · 2019-02-20 20:11:27

计算一个数的 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 语言教程 文章: https://codercto.com/courses/l/17.html

查看所有标签

PHP经典实例(第3版)

PHP经典实例(第3版)

David Sklar、Adam Trachtenberg / 苏金国、丁小峰 / 中国电力出版社 / 2015-7 / 128.00

想要掌握PHP编程技术?或者想要学习如何完成一个特定的任务?那么一定要先看看《PHP经典实例(第3版)》。本书介绍了专门为PHP 5.4和5.5修订的350个经典技巧,并提供了丰富的示例代码。特别是对生成动态Web内容的解决方案做了全面更新,从使用基本数据类型到查询数据库,从调用RESTful API到测试和保护网站安全都有涵盖。 各个技巧都提供了示例代码,可以免费使用,另外还讨论了如何解决......一起来看看 《PHP经典实例(第3版)》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具