简体   繁体   English

在C中第二次执行功能时,如何将f打印到下一行?

[英]How to printf to next line when function is executed for the 2nd time in C?

Solving a problem. 解决问题。 But my output is not matching with the expected output. 但是我的输出与预期的输出不匹配。

Input: 输入:

2
16
10

Expected Output: 预期产量:

16 11 6 1 -4 1 6 11 16
10 5 0 5 10

Actual Result: 实际结果:

16 11 6 1 -4 1 6 11 16 10 5 0 5 10

I have almost tried all the escape sequences, ie "\\n" "\\t" , etc. 我几乎尝试了所有转义序列,即"\\n" "\\t"等。

#include <stdio.h>
#include <stdbool.h>

void printPattern(int n, int m, bool flag) {
    printf("%d ", m);

    if (flag == false && n == m)
        return;

    if (flag) {
        if (m - 5 > 0)
            printPattern(n, m - 5, true);
        else
            printPattern(n, m - 5, false);
    } else 
        printPattern(n, m + 5, false);        

    //return 0;
}

int main() {
    //int n = 16;

    int t, n;
    scanf("%d", &t);

    while (t-- > 0) {
        scanf("%d", &n);
        printPattern(n, n, true);
    }
    return 0;
}

Input: 输入:

2
16
10

Expected Output: 预期产量:

16 11 6 1 -4 1 6 11 16
10 5 0 5 10

Actual Result: 实际结果:

16 11 6 1 -4 1 6 11 16 10 5 0 5 10

You just need to print a linefeed after you invoke printPattern in the loop. 在循环中调用printPattern后,只需打印换行符。

while(t-->0){
    scanf("%d", &n);
    printPattern(n,n,true);
    printf("\n");
}

I wouldn't put the linefeed print in the recursive printPattern function itself. 我不会将换行打印放在递归的printPattern函数本身中。 You want to print one line for each number you're reading from input and this solution best reflects your intent. 您想为从输入中读取的每个数字打印一行,而该解决方案最能体现您的意图。

You could also do putchar('\\n') instead of printf . 您也可以执行putchar('\\n')代替printf

Add printf("\\n") after the second time you call printPattern() : 第二次调用printPattern()之后,添加printf("\\n") printPattern()

void printPattern(int n,int m, bool flag)
{
    printf("%d ", m);
    if(flag == false && n==m)
        return;
    if(flag)
        if(m-5>0)
            printPattern(n,m-5, true);
        else
        {
            printPattern(n,m-5,false);
            printf("\r\n"); /* Sometimes the carriage return is required in Windows
                               operating systems to simulate line break... */
        }
    else 
      printPattern(n,m+5,false);        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM