Simple simulation algorithm 2

PAT B1036 and Obama together to learn arithmetic, very, very simple a question: with characters printed side length specified for the rectangle n, here is what I see written by someone else answers, conventional thinking is to divide the first and last lines, and 2 ~ n-1 line, but because the proportion of ranks in order to make the console display more like a rectangle, printed only n / 2 rows.

General answer:

. 1 #include <cstdio>
 2  
. 3  int main () {
 . 4      int n-; // edge length 
. 5      char C; // character 
. 6      Scanf ( " % D% C " , & n-, & C);
 . 7  
. 8      // first line 
. 9      for ( int I = 0 ; I <n-; I ++ ) {
 10          the printf ( " % C " , C); // n-characters 
. 11      }
 12 is      the printf ( " \ n- ");
 13 is  
14      // of the 2 ~ n / 2-1 line 
15      for ( int I = . 1 ; I <n-/ 2 - 2 ; I ++ ) {
 16          the printf ( " % C " , C); // for each row The first C 
. 17          for ( int J = 0 ; J <n-- 2 ; J ++ ) {
 18 is              the printf ( "  " ); // n-2-spaces 
. 19          }
 20 is          the printf ( " % C \ n- ", c);
21     }
22 
23     // 第n/2行
24     for (int i = 0; i < n; i++) {
25         printf("%c", c);
26     }
27 
28     return 0;
29 }

running result:

Although it is a very simple question was, but I have another ordinary "conventional" get solutions:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int n;
 7     char c;
 8     cin >> n >> c;
 9     for (int i = 0; i < n / 2; i++) {
10         for (int j = 0; j < n; j++) {
11             if (i == 0 || i == n / 2 - 1 || j == 0 || j == n - 1) {
12                 cout << c;
13             } else {
14                 cout << ' ';
15             }
16         }
17         cout << endl;
18     }
19     return 0;
20 }

Comparison of two ways, the first is handled by computer to computer printing characters the way: The Spring River Flows East, waterfalls three thousand feet. While the second is in accordance with the ordinary way to draw a rectangle to realize: if they had four sides.

While solving the same problem, but a different way of thinking it can make the code more streamlined, it is worth pondering.

Guess you like

Origin www.cnblogs.com/viewts/p/11237914.html