c - 学习 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
但它会用额外的一行空格打印它。
解决方案
您首先打印数字,然后打印一些比您当前正在处理的数字多一个的空白。
反过来,即首先打印适当的许多空白,然后打印数字。
并且适当地,许多空白仅与您正在打印的数字一样多,即比您当前的数量少一个。即第一个“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()
. 不这样编写代码会使程序容易受到错误语法输入的影响。
推荐阅读
- javascript - 如何在 if-else 函数中使用 jquery 更改按钮文本
- java - 二叉树的前序遍历打印出我不想要的额外值
- maven - Mule域项目依赖使用maven失败
- c++ - std::uniform_real_distribution 与 std::uniform_int_distribution 性能
- php - 如何在单击按钮时运行 mysql 查询
- c# - EF Core 代码优先与同一主体实体的多个外键关系
- python - 如何使用 tkinter 正确处理表格?
- python - networkx 在左侧和右侧绘制单独的节点 - graphviz,python
- algorithm - 高效查询庞大文档集合中的短语
- plotly-dash - 如何在 Dash-Plotly 中包含基于条件的跟踪