为什么这个位置1能正确输出ch,位置2就不能输出ch了

我在写洛谷题https://www.luogu.com.cn/problem/P1838
的时候遇到了问题,

#include
using namespace std;
const int N=110;
string x;
char g[10];
int flag;
char ch;
signed main()
{
    cin>>x;
    for(int i=0;i1)%2!=0)    g[x[i]-'0']='x';
        if((i+1)%2==0)    g[x[i]-'0']='o';
    }
    if(g[1]==g[2]&&g[2]==g[3]) ch=g[1],flag=1;
    if(g[4]==g[5]&&g[5]==g[6]) ch=g[4],flag=1;
    if(g[7]==g[8]&&g[8]==g[9]) ch=g[7],flag=1;
    
    if(g[1]==g[4]&&g[4]==g[7]) ch=g[1],flag=1,cout<" "<<"test0"<2]==g[5]&&g[5]==g[8]) ch=g[2],flag=1;
    if(g[3]==g[6]&&g[6]==g[9]) ch=g[3],flag=1;
    
    if(g[1]==g[5]&&g[5]==g[9]) ch=g[1],flag=1;
    if(g[3]==g[5]&&g[5]==g[7]) ch=g[3],flag=1;
    cout<" "<<"test1"<1)
    {
        if(ch=='x') cout<<"xiaoa wins.";
        if(ch=='o') cout<<"uim wins.";
    }else{
        cout<<"drew.";
    }
    return 0;
}

img


为什么这个位置1能正确输出ch,位置2就不能输出ch了

img


加了goto后就能ac了,这是为什么啊。。

#include
using namespace std;
const int N=110;
string x;
char g[10];
int flag;
char ch;
signed main()
{
    cin>>x;
    for(int i=0;iif((i+1)%2!=0)    g[x[i]-'0']='x';
        if((i+1)%2==0)    g[x[i]-'0']='o';
    }
    if(g[1]==g[2]&&g[2]==g[3]) 
    {
        ch=g[1],flag=1;goto end;
    }
    if(g[4]==g[5]&&g[5]==g[6]) 
    {
        ch=g[4],flag=1;goto end;
    }
    if(g[7]==g[8]&&g[8]==g[9]) 
    {
        ch=g[7],flag=1;goto end;
    }
    if(g[1]==g[4]&&g[4]==g[7]) 
    {
        ch=g[1],flag=1;goto end;
    }
    if(g[2]==g[5]&&g[5]==g[8]) 
    {
        ch=g[2],flag=1;goto end;
    }
    if(g[3]==g[6]&&g[6]==g[9]) 
    {
        ch=g[3],flag=1;goto end;
    }

    if(g[1]==g[5]&&g[5]==g[9]) 
    {
        ch=g[1],flag=1;goto end;
    }
    if(g[3]==g[5]&&g[5]==g[7]) 
    {
        ch=g[3],flag=1;goto end;
    }
    end:
    if(flag==1)
    {
        if(ch=='x') cout<<"xiaoa wins.";
        if(ch=='o') cout<<"uim wins.";
    }else{
        cout<<"drew.";
    }
    return 0;
}

在第10行的语句 g[x[i]-'0']='x'; 中,下标 x[i]-'0' 可能会超出数组 g 的索引范围,导致未定义行为。因为 x[i] 表示的是 char 类型的字符,需要将其转换成整数类型才能计算出正确的下标。

在第10行和第12行,应该将 g[x[i]-'0'] 修改为 g[static_cast(x[i]-'0')],以避免下标越界的问题。

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/7767986
  • 你也可以参考下这篇文章:大数据助力创建数字化智慧城市解决方案
  • 除此之外, 这篇博客: C语言递归函数练习中的 Problem E:【递归】利用辗转相除法求最大公约数 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

    题目描述
    本题要求实现一个递归函数:利用辗转相除法求最大公约数。
    函数接口定义:
    int gcd(int a, int b);
    裁判测试程序样例:
    在这里插入图片描述
    辗转相除法,是目前已知最古老的算法, 可追溯至公元前300年。
    它首次出现于欧几里德(Euclidean)的《几何原本》(第VII卷,命题i和ii)中,在中国可以追溯至东汉时期的《九章算术》
    辗转相除法计算两个正整数a和b的最大公约数,步骤描述如下:
    (1) 如果b为0则最大公约数为a,算法结束
    (2) 令r为a÷b所得余数
    (3) 令a←b,b←r,并返回步骤(1)


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^