我仍在学习 C 编程,需要一些帮助。我正在尝试编写一个程序,以在二维字符数组中进行搜索,并告诉您所搜索的字符在二维数组中相对于 (x,y) 坐标的位置。我的问题是程序不能输出正确的 (x, y) 坐标。
现在我认为程序应该输出 B 的 (1,0),(1,1),(1,2),(1,3),(1,4)。我还计划调整坐标,使其从1开始计数,而不是从0开始,例如,对于B,输出应为 (2,1),(2,2),(2,3),(2,4),(2,5)。到目前为止,唯一正确输出的坐标是 (1,1),我不确定代码出了什么问题。我应该怎么做来解决这个问题?
完整代码如下:
完整代码如下:
#define _CRT_SECURE_NO_WARNINGS
#define SIZE 5
#include <stdio.h>
int main()
{
int c, count = 0;
int x[SIZE] = { 0 };
int y[SIZE] = { 0 };
int j, i;
char array[SIZE][SIZE] = { { 0 }, { 0 } };
char array2[SIZE] = { 'A', 'B', 'C', 'D', 'S' };
char search;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
array[i][j] = array2[j];
}
}
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
printf("%c ", array[i][j]);
}
printf(" \n");
}
printf("What letter are you lookiong for? ");
scanf("%c", &search);
for (j = 0; j < 5; j++)
{
for (c = 0; c < 5; c++)
{
if (array[j][c] == search)
{
y[j] = j;
x[c] = c;
count++;
}
}
}
if (count == 0)
printf("%c is not present in array.\n", search);
else
{
for (i = 0; i < count; i++)
{
printf("%c is present at (%d , %d) times in array.\n", search, x[i], y[i]);
}
}
return 0;
}
array[row][column]
的方式来访问数组元素,而您所偏爱的答案似乎使用了 Array(Column,Row)(或 A(C,R))的表示法。这只是一种表现形式的问题,但如果您使用 A(C,R) 表示法,很可能会感到困惑。至少,您需要意识到这种行为。 - Jonathan Leffler