c - C 中的递归和 printf

标签 c

我的教授让我这样做:

Input Number: 5
+++++
+++++
+++++
+++++
+++++

我一直在努力得到你;我一直以一个带有巨大空白的“+”结尾 "+ "。

你能帮我用 C 修改这段代码吗?

#include <stdio.h>
#include <conio.h>
int space(int space1)
{
    if(space1 == 0)
    {
        return 1;
    }
    else
    {
        return printf("\n") && space(space1 - 1);
    }
}
int visual(int plus)
{
    if (plus == 0)
    {
        return 1;
    }
    else
    {
        return printf("+") && visual (plus - 1) && space(plus - 1);
    }
}

int main()
{
    int number;
    printf("Please give the number\n");
    scanf("%d",&number);
    visual(number);
    getch();
}

一个新的编辑;令我沮丧。它给了我 5 行 + 和一个大空间。

最佳答案

在 if (plus == 0) 部分的递归函数中,您应该打印\n 字符,然后使用循环调用 visual (number) 次数。

如果你真的只想用递归来做,你还需要另一个递归函数。 一个递归函数将调用另一个,一个将打印“++++++\n”,另一个将调用此函数 x 次以产生 x 行数。

 function printpluses (int x){
     if (x==0){
         printf ("\n");
         return;
     }
     else {
          printf ("+");
          printpluses (x-1);
     }
 }

另一个函数是

  function printline (int x, int no_of_pluses){
       if (x==0){
          printf ("\n");
          return;
       }
       else{
           printpluses(no_of_pluses);
           printline (x-1, no_of_pluses);
       }
   }

您可以将 no_of_pluses 设为全局,这样您就不会在每次调用时都传递它。

关于c - C 中的递归和 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8877115/

相关文章:

c - SOL_SOCKET 有什么用?

c - 在什么条件下管道读取是原子的?

c - 使用 fscanf 时调试 seg 错误时出现问题

c - 头文件中的完整宏

c - 登录脚本未按预期比较字符串输入

c - 每 20 秒打印一次消息的信号(C 多线程程序)

c - 如何在 C 中获取 0's of digits when iterating through int'

C - 作为 void ptr 传递到 int 列表的 ptr 地址 - 使用 int 或 const int?

python - numpy 中的等效函数

C: 找不到文件中定义的函数的符号?