我需要帮助创建一个可以搜索数组的函数
I need help creating a function that can search an array
以下是问题:
- 创建一个函数,通过在数组中查找乘积来返回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;
}
相关文章:
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 这是一个二叉搜索树吗?黑客排名问题
- 如果你有一个固定大小的数组,你需要遍历它!n次,使用二进制搜索如何改变时间复杂性
- 在结构向量中搜索一个数据成员,然后打印匹配的所有数据成员
- Rcpp ,在文件中搜索一个值
- 从另一个向量中搜索和找到元素的有效方法
- 将一个不充实的二进制搜索树转换为完整的二进制搜索树
- 如何在 中输入记录的一个字段时搜索记录
- 如何编写一个 void 函数,该函数将在数组中搜索值,并通过引用将该值的位置传递回 main 函数
- C 搜索数组以获取一个数字,但如果找不到该数组,则不会触发其他语句
- 通过搜索下一个字符来出乎意料的行为
- 从C++二进制搜索树中删除一个节点(类而非结构)
- 哪种数据结构是在一个向量中搜索和计数对象对的最佳数据结构
- 为什么我的原始二叉搜索树被修改,即使我在另一个节点中复制了根节点
- 从文件搜索搜索单词,然后将整个行复制到另一个文件
- 在Java中使用一个或更多单词搜索整个数据库
- 在C++中为二叉搜索树创建一个删除函数
- C++,我想在字符串中搜索一个字符,并输出包含该字符的所有单词
- 很难从我的二进制搜索树中删除一个节点
- 如何在这个c++程序中创建一个搜索函数