[英]Plotting points using Nested For Loops
I'm relatively new to C++ and we have been given this task to do:我对 C++ 比较陌生,我们被赋予了以下任务:
Write a C++ program which asks the user for a number n between 1 and 10. The program should then print out n lines.
编写一个 C++ 程序,要求用户输入 1 到 10 之间的数字 n。然后程序应该打印出 n 行。 Each should consist of a number of stars of the same number as the current line number.
每个应该由与当前行号相同数量的星号组成。 For example:
例如:
Please enter a number: 5 * ** *** **** *****
The problem I am having is that when I use the code I've written it displays wrong.我遇到的问题是,当我使用我编写的代码时,它显示错误。
The code I have right now reads like this:我现在的代码是这样的:
#include<iostream>
using namespace std;
int main() {
int n;
cout << "Please enter a number between 1 and 10:" << endl;
cin >> n;
for (int x = 0; x <= n; x++)
{
for (int y = 0; y <= n; y++) {
cout << "*" ;
}
cout << "*" << endl;
cin.get();
}
return 0;
}
Step through the logic of your program using pen and paper.使用笔和纸逐步完成程序的逻辑。
For your "horizontal" loop, you go all the way up to n
each time.对于您的“水平”循环,您每次都一直到
n
。 Is that right?那正确吗? I think you meant to go only as far as
x
, as this is the value that increases with each line.我认为你的意思是只到
x
,因为这是每行增加的值。
The other problem is that you have one too many of everything, because you used <=
rather than <
.另一个问题是你拥有的东西太多了,因为你使用了
<=
而不是<
。
The solution is exactly as '@Lightness Races in Orbit' just explained to you.解决方案与刚刚向您解释的“@Lightness Races in Orbit”完全相同。 Let me add that if the requirement is just print out what you showed us, then no need for the last '*' nor the 'cin.get()':
让我补充一点,如果要求只是打印出您向我们展示的内容,则不需要最后一个 '*' 或 'cin.get()':
for (int x = 0; x <= n; ++x)
{
for (int y = 0; y < x; ++y) {
cout << "*" ;
}
// No need for all the rest just print 'new line'
std::cout << "\n";
}
There is no need for a nested loop.不需要嵌套循环。 This program works as well with one for loop.
这个程序也适用于一个 for 循环。
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter a number and press ENTER: ";
cin >> n;
for (int i = n; i < 11; ++i) {
cout << i << " " << endl;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.