我正在從我的教科書有關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
使用數組來存儲結果。 – 2013-03-04 23:47:03