当前位置 : 主页 > 网络编程 > lua >

Lua用一维数组存储一个n阶方阵,输出这个方阵的正对角线上的数的和与反对角

来源:互联网 收集:自由互联 发布时间:2021-06-23
arr = { 11 , 2 , 4 , 4 , 5 , 6 , 10 , 8 , - 12 } function diagonalDifference(arr)dimesion = math.sqrt (# arr) arr1 = {} sum1 = 0 arr2 = {} sum2 = 0 for i= 1 ,dimesion do for j= 1 ,dimesion do if (i == j) then arr1[j] = arr[ 1 + (j - 1 ) * (
arr = {11, 2, 4,
        4, 5, 6,
        10, 8, -12}
function diagonalDifference(arr)
dimesion = math.sqrt(#arr)

    arr1 = {}
    sum1 = 0
    arr2 = {}
    sum2 = 0

    for i=1,dimesion do
        for j=1,dimesion do
            if(i == j)then
                arr1[j] = arr[1 + (j - 1) * (dimesion + 1)]
                sum1 = sum1 + arr1[j]
                --print(arr1[j])
            end
        end
    end


    for i=1,dimesion do
        for j=1,dimesion do
            if((i + j) == (dimesion + 1))then
                arr1[j] = arr[dimesion + (j - 1) * (dimesion - 1)]
                sum2 = sum2 + arr1[j]
                --print(arr1[j])
            end
        end
    end
    return math.abs(sum2 - sum1)

end
print(diagonalDifference(arr))
网友评论