嵌套For循环到Do while循环
Nested For loop to Do while Loop
你好,我看了关于家庭作业问题的指导方针,上面说要清楚地说明这是家庭作业。这是作业,我花了45分钟一遍又一遍地尝试。我遇到了瓶颈,需要帮助。
我的任务是将这段来自双For循环的代码转换为嵌套在For循环中的while循环。我已经成功地完成了。然而,第三部分是使用该代码并将外部for循环变成do while循环。输出需要每行增加一个"#",如果输入为"4"
#
##
###
####
下面是我写的代码,我需要把外部的for循环变成一个do while循环:
int main()
{
int side;
cout << "Enter a number: ";
cin >> side;
for (int i = 0; i < side; i++)
{
int j = i;
while(j >= 0)
{
cout << "#";
j--;
}
cout << "n";
}
}
这是我到目前为止的尝试:
int main()
{
int side;
int i;
cout << "Enter a number: ";
cin >> side;
int j=side;
do
{
while(j >= 0)
{
cout << "#";
j--;
}
cout << "n";
i++;
}
while(j >= side);
}
我的老师说,只要解释了代码,我明白它是如何工作的,这是可以的。任何帮助都将非常感激。谢谢。
你犯的第一个错误是:
int i; //not initialized!
/*...*/
i++;
,你甚至没有在do-while条件中使用它。
所以while(j >= side);
> while (i >= side);
事实上,这也不是真的。因为边是输入,你想让i
检查它是否小于而不是大于。所以是while (i < side);
另一件事是int j=side;
,当你递减j
时,它将永远不会重置,所以你必须将它设置到你的do-while循环中,并使用i
而不是....初始化它
总之,这里是完整的代码:
#include <iostream>
using namespace std;
int main()
{
int side;
int i = 0;
cout << "Enter a number: ";
cin >> side;
do
{
int j = i;
while (j >= 0)
{
cout << "#";
j--;
}
cout << "n";
i++;
} while (i < side);
return 0;
}
示例输出:
Enter a number: 10
#
##
###
####
#####
######
#######
########
#########
##########
我建议
int main()
{
int side;
int i = 0;
cout << "Enter a number: ";
cin >> side;
do
{
int j = i;
while(j >= 0)
{
cout << "#";
j--;
}
cout << "n";
i++;
}while(i < side)
}
for循环通常由初始化(i=0
)、停止条件(i < side
)和递增(i++
)组成;为什么你不再使用i
了?
-
while(j >= side);
应该是while(i <= side);
-
j
应在外循环(j = i;
)的每次迭代中初始化 -
int j=side;
是不必要的。
一个友好的建议-描述性地命名你的变量和函数- row
和column
比i
和j
好得多。
上面的答案解决了你的问题,但让我告诉你一个更简单的方法:
int main()
{
int side;
std::cout << "Enter a number: ";
std::cin >> side;
int row = 1;
do
{
int col = 0;
while (col++ != row)
{
std::cout << "#";
}
std::cout << "n";
} while (row++ != side); //This way, the condition is checked (row != side), and then row is incremented
}
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- OpenCV QT,显示视频的帧(不使用while循环)
- 输入循环 while 函数
- c++中的循环(while)
- 为什么这段代码没有循环(while)