簡體   English   中英

如何在多維數組的主對角線上找到最小的數字?

[英]How can i find smallest number in main diagonal of multidimensional array?

我需要編寫一個程序來加載一個尺寸為 3x3 的整數矩陣,並在第一個對角線上找到最小的元素。 我制作了這段代碼,但它只給了我整個矩陣中最小的 integer:

#include <stdio.h>

int main() {
    int mat[10][10];
    int i,j,smallest;
    printf(" ");
    for(i = 0; i < 10; i++)
        for (j = 0; j < 10; j++)
        scanf("%d", &mat[i][j]);
        smallest = mat[0][0];
    for ( i = 0; i < 10; i++){ 
        for(j = 0; j < 10;  j++){
            if(mat[i][j] < smallest)
            smallest = mat[i][j];
        }
    }
    printf("%d",smallest);
    return 0;
}

你能給我任何解決這個問題的方法嗎?

答案非常簡單,即使在谷歌上你也肯定能找到它。

但這里有一個提示可以找到此類問題的答案:

在紙上畫出這個矩陣。 (如果不是 10x10,請嘗試 2x2,然后是 4x4,然后是 5x5)。 然后只寫下主要對角線元素的索引。

例如,在 4x4 矩陣的情況下,這些將是:

[0][0], [1][1], [2][2], [3][3]

你看到上面的圖案了嗎?

這種模式也將遵循 10x10。

現在,由於您需要在主對角線上找到最小的元素,因此您只需要在主對角線上循環這些元素。 (使用上面的模式為 10x10 設計循環,然后再試一次。)

  1. 使用函數
  2. 使用正確的索引類型( size_t
  3. 當你測試你的代碼時,盡量避免用戶輸入。 它將在調試期間為您節省大量時間。
int findSmallestDiagonal(size_t size, int (*array)[size])
{
    int result = array[0][0];
    for(size_t index = 1; index < size; index++)
        if(array[index][index] < result) result = array[index][index];
    return result;
}

void fillOrPrint(size_t size, int (*array)[size], int print, int max)
{
    for(size_t r = 0; r < size; r++)
    {
        for(size_t c = 0; c < size; c++)
        {
            if(print) printf("[%6d] ", array[r][c]);
            else array[r][c] = rand() % max;
        }
        if(print) printf("\n");
    }

}

#define SIZE 16

void main()
{
    int array[SIZE][SIZE];
    int smallest;

    srand(time(NULL));

    fillOrPrint(SIZE, array, 0, 1000); //fill array
    fillOrPrint(SIZE, array, 1, 0);    //print array

    smallest = findSmallestDiagonal(SIZE, array);

    printf("The smalles diagonal is: %d\n", smallest);
}

https://godbolt.org/z/75fzj8Tsq

以下代碼將對此有所幫助,

    #include <stdio.h>

int main() {
    int mat[3][3];
    int i,j,smallest;
    printf(" ");
    for(i = 0; i < 3; i++)
        for (j = 0; j <3; j++)
        scanf("%d", &mat[i][j]);
        smallest = mat[0][0];
    for ( i = 0; i < 3; i++){ 
        for(j = 0; j < 3;  j++){
            if(i==j)     //logic for main diagnol
                if(smallest>mat[i][j])
                    smallest = mat[i][j];
        }
    }
    printf("%d",smallest);
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM