2013-03-04 90 views
0

我正在從我的教科書有關2維數組的樣本。它有以下示例,它允許用戶輸入一個值,然後它搜索該數組並返回包含該值的元素的位置,或者在該值不存在時向其發出警報。C:搜索一個數組並返回多個值

我在想什麼,如果多個元素包含用戶的價值?在代碼中,我添加了一些循環來初始化2d數組,並且多個元素包含相同的值。我將如何設置搜索以返回包含搜索值的多個元素?

#include <stdio.h> 

int main() { 

int iTwoD[3][3]; 
int iFoundAt[2] = {0}; 
int x, y; 
int iFound, iValue = 0; 


//initialize the 2-d array 
for (x = 0; x<=2; x++) { 

    for (y=0;y<=2;y++) 
    iTwoD[x][y] = (x+y); 
} //end outer loop 

//print the 2-d array 
for (x=0; x<=2; x++){ 

    for (y=0;y<=2;y++) 
    printf("iTwoD[%d][%d] = %d\n", x, y, iTwoD[x][y]); 

}//end outer loop 

//Get the user's value to search for 
printf("\nEnter your search value: "); 
scanf("%d", &iValue); 

//Search the 2-d array for user's value 
for (x = 0; x<=2; x++) { 
    for (y = 0; y<=2; y++) { 
    if (iTwoD[x][y] == iValue) { 
     iFound = 1; 
     iFoundAt[0] = x; 
     iFoundAt[1] = y; 
     break; 
    } //end if 
    } //end inner loop 
} //end outer loop 

if (iFound ==1) 
    printf("\nFound value in iTwoD[%d][%d]\n", iFoundAt[0], iFoundAt[1]); 
else 
    printf("\nValue not found\n"); 

return 0; 
} //end main 
+0

使用數組來存儲結果。 – 2013-03-04 23:47:03

回答

1
if (iTwoD[x][y] == iValue) 
{ 
    arrayOfResults[i][0]=resultx; 
    arrayOfResults[i++][1]=resulty; 
} 
+0

找到單個結果後,它不會停止循環,而是一直保持到2d數組結束並將所有正確的結果存儲在數組中 – 2013-03-05 11:32:50

1

你需要增加你的iFoundAt要能容納比(X,Y)一個元組了。另外,您需要從搜索中刪除break,因爲您需要搜索整個矩陣,儘管找到了值。

相關問題