gpt4 book ai didi

c++ - 如何调用函数来搜索二维数组的元素?

转载 作者:行者123 更新时间:2023-11-28 04:16:15 25 4
gpt4 key购买 nike

我正努力完成作业,但出了点问题。

如果二维数组在主函数中,我想调用一个函数,它的任务是在二维数组中搜索一个元素,用户在主函数中输入想要的元素。如果找到了想要的元素,调用一个函数来找到它的阶乘,然后在主函数中打印结果,否则,调用另一个函数来显示没有找到想要的元素。

我已经使用 Visual Studio 2019 和 Dev C++ 尝试了这些代码行。

我的程序执行大约 13 个任务,我将它们组织在一个 Switch 语句中,执行该任务的案例是案例 9。

但是一旦我输入要在控制台中搜索的元素。如果该元素存在于数组中,则输出始终显示如下:“ 编号 3 发现位置:4 3 的阶乘是:63个“用户输入的是 3 还是数字。

即使没有找到,输出也是一样。

#include <iostream>
using namespace std;

// declaring a function to search within B1 array.
int search_B1(int[][3], int, int);

// declaring a function to find the fatorial of the found element.
int fact_num(int);

// declaring a function to print out a searching error.
void search_error();

// This is the main function. Program execution begins and ends here.
int main()
{
int B1[3][3], i, j;

cout << " - Please enter the elements of B1 array: \n";
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
cout << "B1[" << i << "]" << "[" << j << "] = ";
cin >> B1[i][j];
}
}
...
...
...
case 9:
{
int num;
cout << endl << " Enter the element to search in B1 array: ";
cin >> num;
cout << endl << search_B1(B1, 3, num) << endl;
break;
}
}

/**********************************************************************/

// This function is called when user inserts '9'
int search_B1(int B1[][3], int num , int)
{
int i, j, flag = 0;

for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
if (num == B1[i][j])
{
flag = 1;
cout << " Number " << num << " Found at position: " << j + 1 << endl;
fact_num(num);
break;
}
}
}

if (flag == 0)
{
search_error();
}
return num;
}
/**********************************************************************/

// This function relates to ' search_B1 ' function.
int fact_num(int num)
{
int fact = 1, f;
for (f = 1; f <= num; f++)
{
fact *= f;
}
cout << " Factorial of " << num << " is: " << fact;
return fact;
}
/**********************************************************************/

// This function relates to ' search_B1 ' function.
void search_error()
{
cout << " The wanted number was not Found in the array!";
}
/**********************************************************************/

我希望搜索的输出是这样的:例子:如果用户将数组元素输入为“1 2 3 4 5 6 7 8 9”并搜索元素“9”

如果找到了想要的元素: 输出将是:

“第 9 号发现位置:4 9 的阶乘是:362880"

如果没有找到想要的元素: 输出将是:

“数组中没有找到想要的号码!”

最佳答案

你有未定义的行为填充和搜索数组

for (i = 1; i <= 3; i++) // B[3][j] is never an element
{
for (j = 1; j <= 3; j++) // B[i][3] is never an element

数组索引从0开始,如果要显示从1开始的索引,在输出中做算术运算

for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
std::cout << "B1[" << (i + 1) << "]" << "[" << (j + 1) << "] = ";
std::cin >> B1[i][j];
}
}

关于c++ - 如何调用函数来搜索二维数组的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56540369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com