簡體   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