[英]How to printf to next line when function is executed for the 2nd time in C?
解決問題。 但是我的輸出與預期的輸出不匹配。
輸入:
2
16
10
預期產量:
16 11 6 1 -4 1 6 11 16
10 5 0 5 10
實際結果:
16 11 6 1 -4 1 6 11 16 10 5 0 5 10
我幾乎嘗試了所有轉義序列,即"\\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;
}
輸入:
2
16
10
預期產量:
16 11 6 1 -4 1 6 11 16
10 5 0 5 10
實際結果:
16 11 6 1 -4 1 6 11 16 10 5 0 5 10
在循環中調用printPattern后,只需打印換行符。
while(t-->0){
scanf("%d", &n);
printPattern(n,n,true);
printf("\n");
}
我不會將換行打印放在遞歸的printPattern
函數本身中。 您想為從輸入中讀取的每個數字打印一行,而該解決方案最能體現您的意圖。
您也可以執行putchar('\\n')
代替printf
。
第二次調用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.