gpt4 book ai didi

C - HoneSTLy 对这种奇怪的行为感到不知所措

转载 作者:行者123 更新时间:2023-11-30 18:26:40 25 4
gpt4 key购买 nike

所以...我花了一个上午的大部分时间来编写一小段代码。这只是一个帮助我记住语法等的小项目。我显然错过了某种巨大的错误,因为代码由于我不明白的原因返回了段错误。

#include <stdio.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <getopt.h>

struct cards
{
int card_value[99];
char card_name[99];
char card_suit[99];
int card_tally;
};

struct cards hand[2];

void tally (int a)
{
int k, j;
for (k=0; k<5; k++)
{
j = j + hand[a].card_value[k];
}
hand[a].card_tally = j;
}

void check_for_ace (int a)
{
int d;
for (d=0; d>5; d++)
{
if (hand[a].card_name[d] =='A')
{
int y;
int z = 10;
for (y=0; y<5; y++)
z = z + hand[a].card_value[y];
if (z < 22)
hand[a].card_value[d]=10;
else
hand[a].card_value[d]=1;
}

}
}

void draw_card (int a)
{
int z = 1 + rand () % 13;
int x=0;

while (hand[a].card_value[x] != 0)
{ x++; }

if ((z > 1) && (z < 10))
{
hand[a].card_value[x]=z;
hand[a].card_name[x]=((char) '0' + z);
}
else if (z == 10)
{
hand[a].card_value[x]=z;
hand[a].card_name[x]='T';
}
else if (z == 11)
{
hand[a].card_value[x]=10;
hand[a].card_name[x]='J';
}
else if (z == 12)
{
hand[a].card_value[x]=10;
hand[a].card_name[x]='Q';
}
else if (z == 13)
{
hand[a].card_value[x]=10;
hand[a].card_name[x]='K';
}
else if (z == 1)
{
/*Function 'check_for_ace' deals with this more properly*/
hand[a].card_value[x]=1;
hand[a].card_name[x]='A';
}
check_for_ace(a);
tally(a);
}



void display_hands ()
{
int x;
printf("\nDealer's Hand Shows: ");
for (x=0; hand[0].card_name[x]!=0; x++)
{
printf("%c ", hand[0].card_name[x]);
}

printf("\nPlayer's Hand Shows: ");
for (x=0; hand[1].card_name[x]!=0; x++)
{
printf("%c ", hand[1].card_name[x]);
}
}

void dealer_turn()
{
while (hand[0].card_tally < 17)
draw_card(0);
}

void player_turn()
{
int op=0;
while (op != 2)
{
printf("What would you like to do?\n");
printf("(1)it or (2)tand\n");
scanf("%d", &op);
if (op == 1)
draw_card(1);

}
}

int main(int argc, char **argv)
{
srand(time(NULL));


draw_card(0);
draw_card(1);
draw_card(1);
display_hands();
player_turn();

dealer_turn();
display_hands();

return 0;
}

现在,真正奇怪的是,看到player_turn和dealer_turn之间的空行了吗?如果我将 display_hands 放在那里,代码执行时不会出错。

有什么想法吗?

此外,我意识到我确实使用了不需要的 header 。我计划稍后使用它们,并将它们留在这篇文章中,这样我就可以将所有内容都保留为错误所在。

最佳答案

在执行此行之前,您没有初始化 j。

  j = j + hand[a].card_value[k];

当我向您的代码添加 j=0 初始化时,它不再崩溃。

例如

void tally (int a)
{
int k, j;
j=0; /* <----- added this line */
for (k=0; k<5; k++)
{
j = j + hand[a].card_value[k];
}
hand[a].card_tally = j;
}

关于C - HoneSTLy 对这种奇怪的行为感到不知所措,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15165601/

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