【问题标题】:C: searching an array and returning multiple valuesC:搜索数组并返回多个值
【发布时间】:2013-02-19 05:29:34
【问题描述】:

我正在研究我教科书中关于二维数组的样本。它具有以下示例,允许用户输入一个值,然后它搜索数组并返回包含该值的元素的位置,或者如果该值不存在则提醒他们。

我想知道,如果多个元素包含用户的值怎么办?在代码中,我添加了一些循环来初始化二维数组,并且多个元素包含相同的值。我将如何设置搜索以返回多个包含搜索值的元素?

#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

【问题讨论】:

  • 使用数组存储结果。

标签: c arrays search


【解决方案1】:

您需要增加您的 iFoundAt 才能容纳多个 (x,y) 元组。此外,您需要从搜索中删除 break,因为尽管找到了值,您仍需要搜索整个矩阵。

【讨论】:

    【解决方案2】:
    if ( iTwoD[x][y] == iValue)
    {
       arrayOfResults[i][0]=resultx;
       arrayOfResults[i++][1]=resulty;
    }
    

    【讨论】:

    • 它不会在找到单个结果后停止循环,而是一直循环到二维数组的末尾并将所有正确的结果存储在一个数组中
    猜你喜欢
    • 1970-01-01
    • 2015-08-21
    • 2013-08-29
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 2013-07-29
    • 1970-01-01
    相关资源
    最近更新 更多