如何解决如何在if语句中比较二维数组3个字符元素?
在第 20、27、32、36 行中,即使该值为真,计数值在最后并未增加,但显示为 0 计数值。我想我在比较数组时犯了一个错误。我不知道如何比较字符元素二维数组
输入是
1
xxx
哦
答案必须是 3 代码如下
#include <stdio.h>
int main()
{
int n;
scanf("%d",&n);
for (int i = 0; i < n; n++)
{
int count = 0;
char t[2][2];
for (int i = 1; i <= 3; i++)
{
scanf("%c %c %c",&t[i][0],&t[i][1],&t[i][2]);
}
if (t[0][0] == '_' || t[0][1] == '_' || t[0][2] == '_' || t[1][0] == '_' || t[1][1] == '_' || t[1][2] == '_' || t[2][0] == '_' || t[2][1] == '_' || t[2][2] == '_')
{
for (int j = 0; j < 3; j++)
{
if (t[j][0] == t[j][1] == t[j][2])
{
20) count++;
}
}
for (int q = 0; q < 3; q++)
{
if (t[0][q] == t[1][q] == t[2][q])
{
27) count++;
}
}
if (t[0][0] == t[1][1] == t[2][2])
{
32) count++;
}
else if (t[0][2] == t[1][1] == t[2][0])
{
36) count++;
}
if (count == 0)
{
printf("%d",2);
}
else if (count == 1)
{
printf("%d",1);
}
else if (count > 1)
{
printf("%d",3);
}
}
}
}
解决方法
下面的代码可能就是您要找的:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,count=0; char s[20];
printf("Enter total number of iterations (n): ");
scanf("%s",s); // Don't use %d. If you use %d and input a character,\
buffer issues arise.
printf("\n");
n = atoi(s);
for (int i = 0; i < n; i++)
{
int count = 0;
char t[3][3];
for (int x = 0; x < 3; x++)
{
printf("Enter 3 chars with spaces between them: ");
scanf(" %c %c %c",&t[x][0],&t[x][1],&t[x][2]); // Space before\
the first %c makes scanf \
skip leading whitespace.
printf("\n");
}
printf("n is %d\n\
t[0][0] = %c,t[0][1] = %c,t[0][2] = %c\n\
t[1][0] = %c,t[1][1] = %c,t[1][2] = %c\n\
t[2][0] = %c,t[2][1] = %c,t[2][2] = %c\n",n,\
\
t[0][0],t[0][1],t[0][2],\
t[1][0],t[1][1],t[1][2],\
t[2][0],t[2][1],t[2][2]);
if (t[0][0] == '_' || t[0][1] == '_' || t[0][2] == '_' || \
t[1][0] == '_' || t[1][1] == '_' || t[1][2] == '_' || \
t[2][0] == '_' || t[2][1] == '_' || t[2][2] == '_')
{
for (int j = 0; j < 3; j++)
{
if ((t[j][0] == t[j][1]) && (t[j][1] == t[j][2]))
{
count++;
}
}
for (int q = 0; q < 3; q++)
{
if ((t[0][q] == t[1][q]) && (t[1][q] == t[2][q]))
{
count++;
}
}
if ((t[0][0] == t[1][1]) && (t[1][1] == t[2][2]))
{
count++;
}
else if ((t[0][2] == t[1][1]) && (t[1][1] == t[2][0]))
{
count++;
}
if (count == 0)
{
printf("%d",2);
}
else if (count == 1)
{
printf("%d",1);
}
else if (count > 1)
{
printf("%d",3);
}
}
}
return(0);
}
输出如下(count
好像是> 1
,所以打印了3
):
Enter total number of iterations (n): 1
Enter 3 chars with spaces between them: x x x
Enter 3 chars with spaces between them: o o o
Enter 3 chars with spaces between them: _ _ _
n is 1
t[0][0] = x,t[0][1] = x,t[0][2] = x
t[1][0] = o,t[1][1] = o,t[1][2] = o
t[2][0] = _,t[2][1] = _,t[2][2] = _
3
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。