首页 > 解决方案 > 学习 zybooks 中的嵌套循环

问题描述

#include <stdio.h>

int main(void) {
   int userNum;
   int i;
   int j;

   scanf("%d", &userNum);

   for(i = 0; i <= userNum; ++i) {
     printf("%d\n",i);
     for (j = 0; j <= i; ++j) {
        printf(" ");
     }
   }
   return 0;
}

它应该打印:

0
 1
  2
   3

但它会用额外的一行空格打印它。

标签: c

解决方案


您首先打印数字,然后打印一些比您当前正在处理的数字多一个的空白。
反过来,即首先打印适当的许多空白,然后打印数字。
并且适当地,许多空白仅与您正在打印的数字一样多,即比您当前的数量少一个。即第一个“0”没有,然后一个“1”。

#include <stdio.h>

int main(void)
{
   int userNum=0; // init, to have a default in case of failing scanf()
   int i;
   int j;

   scanf("%d", &userNum); // you should check the return value here...

   for(i = 0; i <= userNum; ++i)
   {
     for (j = 0; j < i; ++j) // "<" instead of "<=" makes one fewer
     { 
        printf(" ");
     }
     printf("%d\n",i); // afterwards
   }
   return 0;
}

顺便说一句,我建议养成检查scanf(). 不这样编写代码会使程序容易受到错误语法输入的影响。


推荐阅读