菱形不正确打印

时间:2017-03-23 05:16:53

标签: c++ shape

好吧所以我必须创造这种钻石形状,它应该是钻石形状,但右上半部缺失,左下半部分缺失。我有两个形状向下,但它们没有以钻石形状出现,而是在一个在另一个上面打印出来。

我假设在某个地方。我必须打印出相同数量的空格才能将整个底部形状向右移动?

#include <iostream>

using namespace std;

int main()
{
   int row, col, siz;

   cout << "Enter the size of the diamond: " << endl;
   cin >> siz;

   cout << endl << endl;


   for(row = 1; row <= siz; row++){

      for(col = 1; col <= siz; col ++){
         if(col <= siz - row){
            cout << " ";
         }
         else{
                cout << "@";
             }
        }
        cout << "\n";
    }

    for(row = 1; row <= siz; row++){

        for(col = row; col <= siz; col++){
            cout << "@";
        }
        cout << "\n";
    }

    return 0;
}

2 个答案:

答案 0 :(得分:0)

这是我解决问题的方法:

#include <iostream>
using namespace std;

int main()
{
   int row, col, siz;

   cout << "Enter the size of the diamond: " << endl;
   cin >> siz;

   cout << endl << endl;

   // drawing top left side of diamon
   for(row = 1; row <= siz; row++){
      for(col = 1; col <= siz; col ++){
         if(col <= siz - row){
            cout << " ";
         }
         else{
                cout << "@";
             }
        }
        cout << "\n";
    }

    // drawing bottom right side of diamon
    for(row = 1; row <= siz; row++){
        for(col = 1; col <= siz*2-row; col++){
            if(col<siz){
               cout << " "; 
            }
            else{
                cout << "@";
            }
        }
        cout << "\n";
    }

    return 0;
}

<强>解释: 下半场的第一栏必须先画出“siz&#39;时间&#39; &#39;然后&#39; siz&#39;时间&#39; @&#39;。所以它必须循环siz * 2;从那以后你总是有&#39; siz&#39;时间&#39; &#39;然后每次少一个&#39; @&#39;这就是为什么循环应该看起来像for(col = 1; col <= siz*2-row; col++)

答案 1 :(得分:0)

我想分享我的答案,如果我理解你的问题,我认为你要求的是以下形状。

          *
        * *
      * * *
    * * * *
  * * * * *
           * * * * *
           * * * *
           * * *
           * *
           *

它的钻石形状缺少右上角和左下角

#include <iostream>

using namespace std;

int main()
{
   int row, col, size;

   cout << "Enter the size of the diamond: " << endl;
   cin >> size;

   for(row = 1; row <= size; row++){
    for (col = 1; col <= size; col++){
      if(col+row == (size / 2))
        for(int i=0;i<row;i++)
          cout <<"*";
      if(row >= size/2 && col >= size/2 )
        {
          if( col + row < size+size/2)
          cout <<"*";
        }
      else
       cout <<" ";
    }
    cout << endl;
  }

  return 0;
}

我希望你觉得它很有帮助。