创建一个程序,该程序通过线性搜索找到与输入数值匹配的给定二维数组的元素。考虑到可能存在多个匹配项,因此应在搜索完成后显示匹配项的数量。 我要执行的执行结果
% ./a.out
Please enter a number: 1
a [0] [0] is 1
There was one 1 in the element of the two-dimensional array a
% ./a.out
Please enter a number: 5
a [1] [1] is 5
a [2] [0] is 5
There were two 5s in the element of the two-dimensional array a
% ./a.out
Please enter a number: 27
There are no 27 elements in the 2D array a
实际执行结果
./a.out
Please enter a number: 1
a [0] [0] is 1
There were 32768 1s in the elements of the two-dimensional array a
There is no 1 in the element of the 2D array a
源代码
#include <stdio.h>
#define INDI 3
#define INDJ 4
int main ()
{
int a [INDI] [INDJ] = {
{1, 8, 11, 3},
{9, 5, 0, 7},
{5, 10, 4, 6},
};
int n;
int i;
int yoko;
int tate;
int result;
int count;
/ * Add variable declaration as needed * /
printf ("Enter a number:");
scanf ("% d", & n);
for (tate = 0; tate <3; tate ++) {
for (yoko = 0; yoko <4; yoko ++) {
if (n == a [tate] [yoko]) {
count ++;
printf ("a [% d] [% d] is% d \ n", tate, yoko, n);
printf ("There were% d% d in the element of 2D array a \ n", n, count);
}
}}
printf ("There is no% d in the element of 2D array a \ n", n);
return 0;
}
答案 0 :(得分:0)
我认为您的代码中存在一些问题。我注意到了一些事情:
n
作为输入,但是您没有为整数提供正确的格式说明符。您应该执行scanf ("% d", & n);
而不是scanf ("%d", &n);
。count
字段初始化为零,而是直接将其递增。我认为您应该在使用之前初始化它:int count = 0;
if
块中,如下所示:if (count == 0) {
printf ("There is no %d in the element of 2D array a \n", n);
}
printf
语句应如下所示:printf ("a [%d] [%d] is %d \n", tate, yoko, n);
printf ("There were %d occurences of %d in the element of 2D array a \n", count, n);
当我应用上述更改时,我能够看到预期的输出:
src : $ ./a.out
Enter a number:5
a [1] [1] is 5
There were 1 occurences of 5 in the element of 2D array a
a [2] [0] is 5
There were 2 occurences of 5 in the element of 2D array a
src : $ ./a.out
Enter a number:46
There is no 46 in the element of 2D array a