你如何在序列中找到数字的位置

How do you find the location of a number in a sequence?

本文关键字:数字 位置      更新时间:2023-10-16

假设我有一个序列:int seq[4][4];然后,假设 seq[1][2]=8;序列的其他值不会产生 8。如果我想找到一个序列的值并打印出它是哪一个(例如 1,2 并使 x=1 和 y=2(,我该怎么做?什么

int x,j;
for (int i = 0; i < 4; i++) // looping through row
{
    for(int j = 0; j < 4; j++) //looping through column
    {
       if (seq[i][j] == 8) //if value matches
       {
           x = i; y = j;   //set value
           i = 4;          //set i to 4 to exit outer for loop
           break;          //exit inner for loop
       }
    }
}
int numberBeingSearchedFor = *Any Value Here*;
int array[*numRows*][*numColumns*];
int firstOccuranceRow = -1, firstOccuranceColumn = -1;
for(int i = 0; i < numRows; ++i)
{
    for(int j = 0; j < numColumns; ++j)
    {
        if(array[i][j] == numberBeingSearchedFor)
        {
            firstOccuranceRow = i;
            firstOccuranceColumn = j;
            i = numRows; //Credit to other answer, I've never seen that :) It's cool
            break;
        }
    }
}
if(firstOccuranceRow == -1 || firstOccuranceColumn == -1)
{
   //Item was not in the array
}