2013-03-04 93 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,因为您需要搜索整个矩阵,尽管找到了值。