奇數幻方

來源:互聯網
上載者:User

N階奇數幻方

/*3階矩陣
3*3矩陣,橫豎對角都等於一個恒值 (15)
 分析:
 建立一個3*3二維數組a[3][3],將num=1賦值給a[0][1],然後儲存其下標,a[0][1]的右上方的值等於num++,依次迴圈,
 對於下標,肯定會越界,這裡使用
          int ki = (i-1+3)%3; 
          int kj = (j+1)%3;
便可解決
如果 右上方的位置有元素的話,則將num++賦值給其正下方的位置 
*/
#include<iostream>
using namespace std;

int main()
{
    int i,j;
    int kn;
   
    while (1)     
    {
        cout<<"輸入奇數幻方階數:";
        cin>>kn; 
         while (1)   //判斷輸入的是否是奇數
        {
             if (kn%2==0 || kn<2)
             {
                 cout<<"輸入資料錯誤!請重新輸入奇數:";
                 cin>>kn;
             }
             else
             {
                 break;
             }
        }
        
        int **a = new int*[kn];  //動態分配二維數組
        for ( i=0; i<kn; i++)
        {
            a[i] = new int[kn];
         for ( j=0; j<kn; j++)
         {
                a[i][j] = 0;   //數組初始化為0
            }
        }
   
    //固定第一行中間列的位置為1
        int num = 1;
        i = 0;
        j = kn/2;
        a[0][j] = num;
       
       
        while (num<kn*kn)
        {
            num++;
            int ki = (i-1+kn)%kn;   //儲存右上方x,y座標
            int kj = (j+1)%kn;
   
            if (a[ki][kj] == 0)        //如果右上方元素為空白(還沒有資料填充)
            {
                 a[ki][kj] = num;
                 i = ki;
                 j = kj;
            }
            else  //如果右上方位置有元素 ,則放於其正下方
            {
                i = (ki+2)%kn;
                j = (kj-1+kn)%kn;      //相減 的需加上kn個周期
                a[i][j] = num;
            }
        }
       
        //輸出數組元素
        for (int m=0; m<kn; m++)
        {
            for (int n=0; n<kn; n++)
            {
                cout<<a

[n]<<" ";
            }
            cout<<endl;
        }
       
        //輸出每行沒列的結果
        int sum = 0;
        for (int g=0; g<kn; g++)
        {
            sum = sum+a[0][g];
        }
        cout<<"每行每列及對角線之和為:"<<sum<<endl;
    }   
    system("pause");
    return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.