iT邦幫忙

0

陣列-下標引索問題

1.問題:如何找出4 * 3陣列中最小元素的下標?像是下圖,最小值的下標是(1, 1)
2.程式碼:

# include <stdio.h>
main() 
{
    float a[4][3];
	 int i;
	 int j;
	 
	for(i = 0; i < 4; i = i + 1)
	 	for(j = 0; j < 3; j = j + 1)
	 		scanf("%f", &a[i][j]);
	 
	int k;		
 	for(i = 0; i < 4; i = i + 1)
 		for(j = 0; j < 3; j = j + 1) 
 		{
 			if(a[0][0] > a[i][j])
 			{
 				k = a[0][0];
				a[0][0] = a[i][j];
				a[i][j] = k;
 					
			}
 	
 			
		 }
 
 		printf("min = %.1f\n", a[0][0]);
 		


}

3.顯示畫面
https://ithelp.ithome.com.tw/upload/images/20200914/20128427sVyl4gR5Vv.png

1
listennn08
iT邦研究生 1 級 ‧ 2020-09-14 17:04:49
最佳解答

找最小值不要去動到原本的陣列
多加變數去找 這樣你就能找到索引

# include <stdio.h>

void main() 
{
    float a[4][3];
	int i;
	int j;
	int minI, minJ;
	float min;
	 
	for(i = 0; i < 4; i = i + 1)
    {
	 	for(j = 0; j < 3; j = j + 1)
        {
	 		scanf("%f", &a[i][j]);
        }
    }
	
	min = a[0][0];
	
 	for(i = 0; i < 4; i = i + 1)
 	{
 		for(j = 0; j < 3; j = j + 1) 
 		{
            if(min > a[i][j])
            {
                min = a[i][j];
                minI = i;
                minJ = j;
            }
		}
 	}
 
 	printf("min = %.1f, (%d, %d)\n", min, minI, minJ);
}
1
richardsuma
iT邦大師 1 級 ‧ 2020-09-14 17:43:53

另外解法,借 listennn08 程式改一下。
直接讀進來就可以判斷處裡,主要程式如下:

float min=0.0;
int minI, minJ;

for(i = 0; i < 4; i = i + 1)
{
for(j = 0; j < 3; j = j + 1)
{
scanf("%f", &a[i][j]);
if(min > a[i][j])
{
min = a[i][j];
minI = i;
minJ = j;
}
}

printf("min = %.1f, (%d, %d)\n", min, minI, minJ);

0
海綿寶寶
iT邦大神 1 級 ‧ 2020-09-14 18:11:22
# include <stdio.h>
main() 
{
    float a[4][3];
	 int i;
	 int j;
     int row;
     int col;
	 
	for(i = 0; i < 4; i = i + 1)
	 	for(j = 0; j < 3; j = j + 1)
	 		scanf("%f", &a[i][j]);
	 
	int k;		
 	for(i = 0; i < 4; i = i + 1)
 		for(j = 0; j < 3; j = j + 1) 
 		{
 			if(a[0][0] > a[i][j])
 			{
 				k = a[0][0];
				a[0][0] = a[i][j];
				a[i][j] = k;
 			
                row = i;
                col = j;
			}
 	
 			
		 }
 
 		printf("min = %.1f row=%d column=%d\n", a[0][0], row, col);
}

話說
你前面幾題是解決了沒?
如果解決了
就選個最佳解答做個結案的動作

我要發表回答

立即登入回答