如何在C中使用递归打印?

时间:2017-01-13 14:13:08

标签: c recursion

我想在屏幕上打印1 2 4 8 16 32 64 128 256。但我得到的只是0 0 0 0 0 0 0 0 0。这是我的代码:

#include<stdio.h>
#include<math.h>

void print(int n) {
  if(n<=8) {
    printf(" %d ",pow(2,n));
    return print(n+1);
  }
}

int main() {
  print(0);
  return 0;
}

3 个答案:

答案 0 :(得分:8)

pow是一个浮点函数。它返回double。您无法使用"%d"进行打印(使用不匹配的格式和参数是未定义的行为)。

使用正确的格式(例如"%f")或将结果投射到int。或者为什么不简单地使用二进制算法将值1移位正确的位数。

答案 1 :(得分:7)

pow返回double%d格式说明符需要int

尝试更新printf来电以使用%.0f,或者将pow的结果转换为int代替:

选项1:

#include <stdio.h>
#include <math.h>

void print(int n)
{
    if(n<=8)
    {
        printf("%.0f\n", pow(2, n));
        return print(n+1);
    }
}

int main()
{
    print(0);
    return 0;
}

选项2:

#include <stdio.h>
#include <math.h>

void print(int n)
{
    if(n<=8)
    {
        printf("%d\n", (int) pow(2, n));
        return print(n+1);
    }
}

int main()
{
    print(0);
    return 0;
}

此外,鉴于return print(n+1)的返回类型为print,您不应该使用void。您可以将print重写为一个函数,该函数返回两个n的幂,然后从main访问返回值:

#include <stdio.h>
#include <math.h>

int print(int n)
{
    return (int) pow(2, n);
}

int main()
{
    int i;
    for(i = 0; i <= 8; i++)
        printf("%d\n", print(i));
    return 0;
}

答案 2 :(得分:1)

我在这里发布的解决方案能够生成需要使用的序列:起始值(x变量),因子值(v变​​量)和多个术语值(n变量)

您要求的情况(1 2 4 8 16 32 64 128 256)是x=1; v=2; n=9;

的时间
#include <stdio.h>
#include <stdlib.h>

void print(int x, int v, int n)
{
        printf("%d ",x);
        if (--n)
                print(x*v,v,n);

        return;
}

int main(void)
{
        print(1,2,9);puts("");
        return 0;
}