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
143 views
in Technique[技术] by (71.8m points)

translating algorithm for C++ nested while loop diamond pattern

Here is my homework problem for C++:

The following algorithm is a solution to a problem that uses nested loops to display a diamond pattern. Translate the algorithm below in to a C++ program. Build, run and test the program.

Algorithm Solution:

Start

Declare numRows as constant integer = 7
Declare maxPlus as constant integer = 7
Declare numSpaces as integer
Declare numPluses as integer
Declare row as integer
Declare space as integer
Declare plus as integer

Set row = 1

Repeat while row >= 1 AND row <= numRows
    Set numPluses = 2 * row - 1
    if(numPluses > maxPlus) then
        Set numPluses = 14 - numPluses
    endif

    Set numSpaces = (maxPlus - numPluses) / 2

    Set space = 1
    Repeat while space >= 1 AND space <= numSpaces
        Display( ' ')
        Set space = space + 1
    End Repeat

    Set plus = 1
    Repeat while plus >= 1 AND plus <= numPluses
        Display( '*')
        Set plus = plus + 1
    End Repeat  

    Set row = row + 1

    Display a new line
End Repeat

Stop

My code:

   #include <iostream>
   using namespace std;

   int main() {

    const int numRows = 7;
    const int maxPlus = 7;
    int numSpaces;
    int numPluses;
    int row;
    int space;
    int plus;

    row = 1;

    while((row >=1) && (row <= numRows)){
        numPluses = 2 * row - 1;
        if(numPluses > maxPlus){
            numPluses = 14 - numPluses;
        }
        numSpaces = (maxPlus - numPluses)/ 2;
        space = 1;
        while((space >= 1) && (space <= numSpaces)){
           cout << " ";
           space++;
        }
        while((plus >= 1) && (plus <= numPluses)){
            cout << "*";
            plus++;
        }
        row++;
        cout << endl;
    }

    return 0;
    }

My question is why am I not getting the diamond pattern? I feel like I translated the algorithm correctly, but all I get is a bunch of blank space. Did I read the problem wrong or did I code wrong? screenshot of C++ code

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Before the last while loop:

Set plus = 1

You missed that in your translation.


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

...