对角线问题

对于一个(n,n)大小的矩阵,使得对角线上的元素全为x,其他元素都是y

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    const int n=20;
    int x=4;
    int y=2;
    int M[n][n];
    //method 1 判断是否在对角线上
    /*
    for(int i=0;i<n;++i)
        for(int j=0;j<n;++j)
            if(i==j)
                M[i][j]=x;
            else
                M[i][j]=y;
            M[i][j]=(i==j)?x:y;//效果同上

    //method 2 整体到局部
    for(int i=0;i<n;++i)
        for(int j=0;j<n;++j)
            M[i][j]=y;
    for(int i=0;i<n;i++)
        M[i][i]=x;
        */

    //method 3 循环展开
    for(int i=0;i<n;++i)
    {
        for(int j=0;j<i;++j)
            M[i][j]=y;
        M[i][i]=x;
        for(int j=i+1;j<n;++j)
            M[i][j]=y;
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
            cout<<M[i][j]<<" ";
        cout<<endl;
    }
    system("pause");
    return 0;
}

原文地址:https://www.cnblogs.com/wangtianning1223/p/11425442.html