打印图形本质:看矩阵中每个元素行坐标和列坐标的关系。所以我们可以有两种方法描述该关系。

方法一:for循环

方法二:条件语句

例题1 打印出如下图形

第一步:分别观察空格和符号的行坐标与列坐标的关系   

符号是上三角矩阵,关系是行坐标小于等于列坐标。空格就是剩下的矩阵 

第二步:观察符号本身与行列坐标的关系。

列坐标从0开始,因为这里符号本身等于列坐标+1,所以其实让列坐标从1 开始更方便,这样就可以直接让输出的数字等于列坐标。

注意:这里符号之间也有空格,所以其实打印符号相当于打印符号加空格,打印空格相当于打印空格加空格。

方法一:for循环

#include<bits/stdc++.h>
using namespace std;

int main()
{
	for(int i =1;i <= 9;i++)
	{
		for(int j = 1;j<i;j++)
		{
			cout << "  ";
		}
		for(int j=i;j <= 9;j++)
		{
			cout << j << " ";
			
		}
		cout << endl;
		
	}
	return 0;
}

方法二:if语句

#include<bits/stdc++.h>
using namespace std;

int main()
{
	for(int i =1;i <= 9;i++)
	{
		for(int j =1;j <= 9;j++)
		{
			if(j>= i) cout << j <<" " ;
			else cout << "  ";
		}
		cout << endl;
	}
	return 0;
}

例题2:平方矩阵

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int n;
    while((scanf("%d", &n)) != EOF)
    {
        if(n==0) break;
        else{
            for(int i = 1;i <=n ;i++)
        {
           int k = i - 1;
            for(int j= 1 ;j<=n;j++)
            {
               int t = pow(2, k);
               cout << t << " ";
               k++;
            }
            cout << endl;
        }
        cout << endl;
        }
    }
    return 0;
}

注:pow输出的是浮点型,应该转成整型。

法二:

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int n;
    while((scanf("%d", &n)) != EOF)
    {
        if(n==0) break;
        else{
            for(int i = 0;i <n ;i++)
        {
          
            for(int j= 0 ;j<n;j++)
            {
               int t = pow(2, i+j);
               cout << t << " ";
            
            }
            cout << endl;
        }
        cout << endl;
        }
    }
    return 0;
}

对于正方形打印,用第二种方法,两层相同条件的循环嵌套和if语句比较简单。

对于三角形,菱形打印,常用第一种方法。

推荐文章:https://blog.csdn.net/twlinl0613/article/details/134627612?ops_request_misc=&request_id=&biz_id=102&utm_term=%E6%89%93%E5%8D%B0%E5%9B%BE%E5%BD%A2&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-1-134627612.142^v102^pc_search_result_base2&spm=1018.2226.3001.4187

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐