【问题标题】:How to print this series?(1 \n 2 3 \n 4 5 6 \n 7 8 9 10... ... ...)如何打印这个系列?(1 \n 2 3 \n 4 5 6 \n 7 8 9 10... ... ...)
【发布时间】:2019-04-09 13:33:12
【问题描述】:

我正在尝试打印以下系列:
1
2 3
4 5 6
7 8 9 10
... ... ...
我的程序的输入包含一个整数 n,它决定了要打印的行数。

我尝试对其进行编码,但得到以下输出:
1
2 3
3 4 5
4 5 6 7
... ... ...

#include<stdio.h>
int main()
{
    int n,i,j,t,m;
    scanf("%d", &n);
    for(i=1;i<=n;i++)
    {
        for(j=i,t=1;t<=i;j++,t++)
        {
            printf("%d ",j);
        }
        printf("\n");
    }
}

【问题讨论】:

  • 所以.. 显然输出表明您没有在嵌套循环中将 j 初始化为正确的值。

标签: c loops series


【解决方案1】:

要打印这些数字,您需要一个从1 开始的计数器,每次打印都会增加1,并且永远不会被任何东西重置。像这样调整你的循环:

int main()
{
    int n, i, j, t = 1;
    scanf("%d", &n);
    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= i; j++, t++)
        {
            printf("%d ", t);
        }
        printf("\n");
    }
}

注意t 是如何设置为1 的,并且只是增加了t++ 而无需像以前那样重置。此外,您应该打印t,而不是j

【讨论】:

    【解决方案2】:

    您应该为数字和每行数字的数量维护单独的计数器。

    int nr = 1, target;
    int nrsperline = 1, i;
    
    scanf("%d", &target);
    while (nr <= target) {
        for (i = 0; i < nrsperline; i++) {
             printf("%d ", nr++);
        }
        printf("\n");
        nrsperline++;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-30
      • 2022-06-17
      • 2019-05-15
      • 1970-01-01
      • 2011-09-08
      • 2022-10-08
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      相关资源
      最近更新 更多