当前位置:网站首页>Diagonal problem

Diagonal problem

2021-07-18 00:24:52 qq59043568cf0cd

For one (n,n) Matrix of size , So that all the elements on the diagonal are x, The other elements are 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  Judge if it's on the diagonal 
    /*
    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;// The effect same as above 

    //method 2  Whole to part 
    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  Loop unrolling 
    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;
}

 

版权声明
本文为[qq59043568cf0cd]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/05/20210525221639111b.html