C++使用 WHILE 循环的直角三角形代码
我需要打印这个三角形:
*
**
***
****
*****
******
*******
********
使用 FOR 和 WHILE 循环。我需要帮助,我已经弄清楚了 for 循环版本,我只需将其转换为 while 循环,但我尝试的所有操作都没有给我正确的输出!任何帮助表示赞赏!
到目前为止我的代码:
#include <iostream>
using namespace std;
int main(int argc, char**argv) {
int i = 1;
int j = 1;
int N = 8;
while (i <= N)
{
i = i++;
while(j <= i)
{
cout<<"*";
j = j++;
}
cout<<endl;
}
}
I need to print this triangle:
*
**
***
****
*****
******
*******
********
using a FOR and WHILE loop. I need help, I have already figured out the for loop version I just have to convert it to while loop but everything I try is not giving me the correct output! Any help is appreciated!
My code so far:
#include <iostream>
using namespace std;
int main(int argc, char**argv) {
int i = 1;
int j = 1;
int N = 8;
while (i <= N)
{
i = i++;
while(j <= i)
{
cout<<"*";
j = j++;
}
cout<<endl;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我会给你一个提示(为了让你自己弄清楚):你忘记在内循环之后将
j
设置回1
。就像现在一样,当
j
变为<= i
一次时,它会保持这种状态,并且永远不会再次进入内部循环。另外,虽然它与您的问题没有直接关系,但请确保从不执行
j = j++
或i = i++
;只需执行j++
和i++
(正如 Kshitij Mehta 在评论中所说)。如果您对原因感兴趣,可以阅读此问题及其答案。I'll give you a hint (in the interest of making you do some figuring out yourself): You're forgetting to set
j
back to1
after the inner loop.As it is now, when
j
gets to be<= i
once, it stays that way and the inner loop is never entered again.Also, while it's not directly related to your question, make sure never to do
j = j++
ori = i++
; just doj++
andi++
(as Kshitij Mehta said in the comments). If you're interested in why, you can read this question and its answers.规则是什么?
What are the rules?
我也会给你一个提示:
i = i++;
并没有像你想象的那样做。I'll give you a hint as well:
i = i++;
doesn't do what you think it does.我真的不知道如何使它比这更简洁:
或者对于循环,减少一行
如果您不介意一些效率较低的代码:
I don't really know how to make it more succinct than this:
or as for loop, cutting down a line
If you don't mind some less efficient code:
我看不到你的三角形,但我认为你需要在 j 上的 each 循环之前将 j 设置为 1:
I can't see your triangle, but I think you need to set j to 1 before each loop on j: