使用 WHILE 循环的直角三角形的 C++ 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7210075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ code for right triangle using WHILE loop
提问by future
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!
使用 FOR 和 WHILE 循环。我需要帮助,我已经找到了 for 循环版本,我只需要将它转换为 while 循环,但我尝试的一切都没有给我正确的输出!任何帮助表示赞赏!
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;
}
}
回答by Seth Carnegie
I'll give you a hint (in the interest of making you do some figuring out yourself): You're forgetting to set j
back to 1
after the inner loop.
我会给你一个提示(为了让你自己搞清楚):你忘记j
回到1
内部循环之后。
As it is now, when j
gets to be <= i
once, it stays that way and the inner loop is never entered again.
就像现在一样,当它j
出现<= i
一次时,它会保持这种状态,并且永远不会再次进入内部循环。
Also, while it's not directly related to your question, make sure neverto do j = j++
or i = i++
; just do j++
and i++
(as Kshitij Mehta said in the comments). If you're interested in why, you can read this question and its answers.
此外,虽然它与您的问题没有直接关系,但请确保永远不要做j = j++
或i = i++
;就做j++
和i++
(正如 Kshitij Mehta 在评论中所说)。如果您对原因感兴趣,可以阅读此问题及其答案。
回答by Jon
I'll give you a hint as well: i = i++;
doesn't do what you think it does.
我也会给你一个提示:i = i++;
不做你认为的那样。
回答by Bo Persson
What are the rules?
规则是什么?
while (1)
{
cout << "*" << '\n';
cout << "**" << '\n';
cout << "***" << '\n';
cout << "****" << '\n';
cout << "*****" << '\n';
cout << "******" << '\n';
cout << "*******" << '\n';
cout << "********" << '\n';
break;
}
回答by sehe
I don't really know how to make it more succinct than this:
我真的不知道如何使它比这更简洁:
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss;
int i = 10;
while (i--)
std::cout << (ss<<'*', ss).str() << std::endl;
}
or as for loop, cutting down a line
或者作为循环,切掉一条线
for(int i=10; i--;)
std::cout << (ss<<'*', ss).str() << std::endl;
If you don't mind some less efficient code:
如果你不介意一些效率较低的代码:
#include <iostream>
int main() { for(int i=1; i<10; std::cout << std::string(i++, '*') << std::endl); }
回答by Nicolas Grebille
I can't see your triangle, but I think you need to set j to 1 before eachloop on j:
我看不到你的三角形,但我认为你需要在 j 上的每个循环之前将 j 设置为 1 :
while (i <= N)
{
i++;
j = 1;
while(j <= i)
{
cout<<"*";
j++;
}
cout<<endl;
}
回答by user10880661
#include <iostream>
using namespace std;
int main()
{
int i, j, N=7;
while(i <= N)
{
i++;
j = 1;
while(j <= i)
{
cout << "*";
j++;
}
cout << endl;
}
}