打印一个有星星的正方形并移除它的对角线

时间:2016-12-09 14:19:24

标签: c++ visual-c++

我正在尝试打印正方形并从右侧移除它的对角线 像

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

我能够使用代码

从左侧移除直径
#include <iostream>
using namespace std;
int main(void)
{
    int h,v,num;
    cout<<"Give a value for length ";
    cin>>v;
    cout<<"Give a value for width ";
    cin>>h;
    for(int i=0;i<v;i++)
    {
        for(int r=0;r<h;r++)
        {
        if (i==r)
            cout<<" ";
        else
            cout<<"*";

        }
        cout<<endl;
    }
}

感谢

2 个答案:

答案 0 :(得分:0)

你可以查看这段代码

#include <iostream>
using namespace std;
int main(void)
{
    int height,width,d;
    cout<<"Give a value for height : ";
    cin>>height;
    cout<<"Give a value for width : ";
    cin>>width;
    d=width-1;
    for(int i=0; i<height; i++)
    {
        for(int j=0; j<width; j++)
        {
            if (j==d)
            {
                cout<<" ";
                d--;
            }

            else
                cout<<"*";

        }
        cout<<endl;
    }
}

答案 1 :(得分:0)

#include <iostream>
using namespace std;
int main(void)
{
    int v;
    cout<<"Give a value for length ";
    cin>>v;
    cout << endl;
    for(int i=0;i<v;i++)
    {
        for(int r=0;r<v;r++)
        {
        if ((i + r) == (v - 1))
            cout<<" ";
        else
            cout<<"*";

        }
        cout<<endl;
    }
}

Try it here!

不要让用户插入宽度和长度,因为无论如何都要打印正方形。如果有人输入两个不同的变量就会出现问题。

从右上角到左下角的对角线上的计算(i + r)始终为(v - 1)。如果你想要它的另一个方向,你可以使用你已经拥有的i == r