C 重写power函数 递归与循环
来源:互联网 发布:枪口动能计算器软件 编辑:程序博客网 时间:2024/05/29 02:18
重写power()函数,返回一个double型的正整数的任意次幂。另外要处理0的任意次幂都为0,任何数的任意次幂都为1(函数应报告0 的 0 次幂未定义,并将该值返回1)。分别使用循环和递归实现。
利用循环程序如下:
#include<stdio.h>
double power(int n, int x);
int main()
{
int num, x;
printf("please enter num and x:");
scanf("%d %d", &num, &x);
printf("%d^%d=%.3lf",num,x, power(num, x));
return 0;
}
double power(int n, int x)
{
double sum = 1;
int i;
if (n != 0)
{
if (x == 0)
return 1;
else
if (x > 0)
{
for (i = 0; i < x; i++)
sum *= n;
return sum;
}
else
{
for (i = 0; i < -x; i++)
sum *= 1.0 / n;
return sum;
}
}
else
if (x ==0)
{
return 1;
printf("0^0 no defined\n");
}
else
return 0;
}
利用递归程序如下:
#include<stdio.h>
double power(int n, int x);
int main()
{
int num, x;
printf("please enter num and x:");
scanf("%d %d", &num, &x);
printf("%d^%d=%.3lf", num, x, power(num, x));
return 0;
}
double power(int n, int x)
{
if (n != 0)
{
if (x > 0)
return n*power(n, x - 1);
else
if (x == 0)
return 1;
else
return 1.0 / n*power(n, x + 1);
}
else
if (x == 0)
{
printf("0^0 no defined\n");
return 1;
}
else
return 0;
}
程序结果:
please enter num and x:3 3
3^3=27.000
please enter another num and x:3 -3
3^-3=0.037
please enter another num and x:5 0
5^0=1.000
please enter another num and x:0 5
0^5=0.000
please enter another num and x:0 0
0^0 no defined
0^0=1.000
please enter another num and x:#
bye!
请按任意键继续. . .
- C 重写power函数 递归与循环
- C fibonaccio 递归与循环
- C语言循环与递归
- 04-02递归与循环关系_重写代码
- C语言中的循环与递归
- C语言之三种循环结构与递归函数的对比
- c语言--函数与递归
- Js 循环、递归、函数
- [示例]存储过程循环与用户自定义函数递归调用
- [示例]存储过程循环与用户自定义函数递归调用
- 递归与循环的开销比较,高精度时间函数
- 二分查找法的C语言实现:递归与循环
- 链表反转C实现(递归与循环)
- 链表反转C实现(递归与循环)
- (C语言)循环与递归求斐波那契数
- C++:函数与递归 Function and Recursion
- C语言04函数与递归
- C语言函数与递归四
- 2016华为校招上机试题2——洞穴逃生
- 3. Longest Substring Without Repeating Characters
- 51.[Python]使用multiprocessing进行多进程编程
- 51nod 1007 正整数分组(01背包)
- Integer Replacement
- C 重写power函数 递归与循环
- Visual Basic 总结
- 有关指针(1)
- Android Studio导入SlidingMenu库
- hdu1241油田
- webdriver+python 对三大浏览器的支持
- 视图总结
- 2063. 【2016.10.4NOIP普及模拟】Exam
- 一个菜鸟java码农的成长之路(4):用LinkedList模拟栈结构