使用嵌套For循环绘制点

Plotting points using Nested For Loops

本文关键字:绘制 循环 For 嵌套      更新时间:2023-10-16

我对c++比较陌生,我们被分配了这个任务:

编写一个c++程序,要求用户输入1到10之间的数字n。然后程序应该打印出n行。每一个都应该包含与当前行号相同数量的星号。例如:

Please enter a number:   5
*
**
***
****
*****     

我遇到的问题是,当我使用我写的代码时,它显示错误。

我现在的代码是这样的:

#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;
}

用笔和纸一步一步地完成你的程序逻辑。

对于你的"水平"循环,你每次都要一直到n。对吗?我想你的意思是只到x,因为这是每一行增加的值。

另一个问题是你有太多的东西,因为你使用<=而不是<

解决方案就像"@Lightness Races in Orbit"刚刚向你解释的那样。让我补充一下,如果需求只是打印您显示给我们的内容,那么不需要最后一个'*'和'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";
}

现场试试!

不需要嵌套循环。这个程序使用一个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;
}