繁体   English   中英

使用嵌套 For 循环绘制点

[英]Plotting points using Nested For Loops

我对 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM