我需要帮助创建一个可以搜索数组的函数

I need help creating a function that can search an array

本文关键字:一个 搜索 数组 函数 帮助 创建      更新时间:2023-10-16

以下是问题:

  • 创建一个函数,通过在数组中查找乘积来返回1和9之间的两个数字的乘积
  • 示例:如果用户输入9和2,程序将在二维数组中查找答案并显示18

我已经做好了表格,我只是不知道如何制作一个可以搜索的功能。

#include <string> 
#include <iostream>
#include <iomanip>  
using namespace std;
int main()
{
    const int numRows = 10;
    const int numCols = 10;
    int product[numRows][numCols] = { 0 };
    for (int row = 0; row < numRows; ++row)
        for (int col = 0; col < numCols; ++col)
            product[row][col] = row * col;
    for (int row = 1; row < numRows; ++row)
    {
        for (int col = 1; col < numCols; ++col)
            cout << product[row][col] << "t";
        cout << 'n';
    }
    return 0;
}

生成数组背后的想法是,所有乘法的可能性都存储在一个表中,以便于查找。没有必要搜索,你只需要在索引中查找值,如下所示:

int result = product[9][2];

标记的顺序也不重要,因为2*9与9*2相同。

我建议您阅读这里的函数或您找到的任何其他好的源代码。

制作一个任意名称的函数,如下所示,传递两个值和2D数组,并使用这种简单的方法提取值

int productvalue(int a,int b, int product[][10])
{
    return product[a][b];
}

完整代码:

#include <string> 
#include <iostream>
#include <iomanip>  
using namespace std;
int productvalue(int a,int b, int product[][10])
{
    return product[a][b];
}
int main()
{
    const int numRows = 10;
    const int numCols = 10;
    int product[numRows][numCols] = { 0 };
    for (int row = 0; row < numRows; ++row)
        for (int col = 0; col < numCols; ++col)
            product[row][col] = row * col;
    for (int row = 1; row < numRows; ++row)
    {
        for (int col = 1; col < numCols; ++col)
            cout << product[row][col] << "t";
        cout << 'n';
    }
    int a,b;
    cin>>a>>b;
    //Example Call to the function
    int x = productvalue(a,b,product);
    cout<<x<<endl;
    return 0;
}