关闭

C primer plus 第九章 练习8:

205人阅读 评论(0) 收藏 举报
分类:
/*
============================================================
    使用递归函数重做练习7.
============================================================
*/

#include <stdio.h>
double power(double n, int p);
int main(void)
{
    double n;
    int p;

    printf("Enter a number and the positive integer power to which\n");
    printf(" the number will be raised. Enter q to quit.\n");
    while(scanf_s("%lf %d", &n, &p) == 2)
    {
        printf("%g to the power %d is %g\n", n, p, power(n, p));
        printf("Enter next pair of numbers or q to quit.\n");
    }
    printf("Hope you enjoyed this power trip -- bye!\n");
    return 0;
}

double power(double n, int p)
{
    double pow;
    if(n == 0) return 0;
    else if(p == 0) return 1;
    else if(p > 0) {
        pow = n * power(n, p-1);
        return pow;
    }
    else if(p < 0) {
        pow = power(n, p+1) / n;
        return pow;
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20930次
    • 积分:974
    • 等级:
    • 排名:千里之外
    • 原创:79篇
    • 转载:4篇
    • 译文:0篇
    • 评论:3条
    文章分类