Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

c++ - Getting input on number of rows then drawing a star in the console

I am currently in week 3 of a c++ college course. We are working on for loops. I am having an issue with the homework.

We are using nested for loops to draw a diamond out to the console made of *s. The homework part of this was to get the user input for the number of rows in the diamond, then print that diamond. I can get user input but I can not get the diamond shape I am left with a triangle.

Any help is appriciated.

This is my current code:

C++

#include<iostream>

using namespace std;

int x;
int y;
int rowNum;

int main(int argc, char *argv[])
{
    cout << " Enter the Numbers of rows you would like between 3 and 15: " << endl;
    cin >> rowNum;

        for(x = 1; x <= 10; x++) //outer loop
        {
            for(y = 1; y <= rowNum; y++){
                if (y <= (10 - x))
                cout << " ";
                else
                cout << "*";
            }
        cout << endl;
        }


    return 0;   
}
question from:https://stackoverflow.com/questions/65936856/getting-input-on-number-of-rows-then-drawing-a-star-in-the-console

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had to do 2 changes in your code to make it work:

  1. Replace all 10 with rowNum

  2. Second outer loop should be

    for (x = rowNum; x >= 1; x--) //outer loop

Note: It works fine only for an even number of rows. You will need to handle the case of an odd number of rows.

Updated code:

std::cout << " Enter the Numbers of rows you would like between 3 and 15: " << std::endl;
std::cin >> rowNum;

for (x = 1; x <= rowNum; x++) //outer loop
{
    for (y = 1; y < x; y++) {
        if (y <= (rowNum - x))
            std::cout << " ";
        else
            std::cout << "*";
    }
    std::cout << std::endl;
}
for (x = rowNum; x >= 1; x--) //outer loop
{
    for (y = 1; y < x; y++) {
        if (y <= (rowNum - x))
            std::cout << " ";
        else
            std::cout << "*";
    }
    std::cout << std::endl;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...