代码细节需注意

来源:互联网 发布:php乘法口诀 编辑:程序博客网 时间:2024/05/17 09:32
将下面的代码变为递归函数循环
原来的代码:
// power.c -- 计算数值的整数次幂
#include <stdio.h>
#include <stdbool.h>
double power(double n, int p); // ANSI 原型
int main(void)
{
    double x, xpow;
    int exp;
    printf("Enter a number and the positive integer power");
    printf(" to which\nthe number will be raised. Enter q");
    printf(" to quit.\n");
    while (scanf("%lf%d", &x, &exp) == 2)
    {
        if(x==0) xpow=0;
        if(exp==0) xpow=1;
        else xpow = power(x,exp);   // 函数调用
        printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
        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 = 1;
    int i;
    bool q;
    q=false;
    if(p<0) p=-p,q=true;
      for (i = 1; i <= p; i++)
       pow *= n;
     if(q)
      pow=1/pow;
    return pow;                // 返回pow值
}
改为递归循环
// power.c -- 计算数值的整数次幂
#include <stdio.h>
#include <stdbool.h>
double abc(double a,int b);
double power(double n, int p); // ANSI 原型
int main(void)
{
    double x, xpow;
    int exp;
    printf("Enter a number and the positive integer power");
    printf(" to which\nthe number will be raised. Enter q");
    printf(" to quit.\n");
    while (scanf("%lf%d", &x, &exp) == 2)
    {
        if(x==0) xpow=0;
        if(exp==0) xpow=1;
        else xpow = power(x,exp);   // 函数调用
        printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
        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;
    int i;
    bool q;
    q=false;
    if(p<0) p=-p,q=true;
    pow=abc(n,p);
    if(q) pow=1/pow;
    return pow;                // 返回pow值
}
double abc(double a,int b)
{
    double q;
    q=1;

    if(b>1)
       q=abc(a,b);
    b--;
    q*=a;
    return q;
}
时发现可运行但输入时会未响应
于是带入值 1 2
开始研究函数
原来是没注意b--使递归成了死循环
于是把b--;
放到q=abc(a,b);
后面还是不行,
就干脆放到if前面
运行通过
高级评论编辑器暂时无法加载
原创粉丝点击