我从书中将“洗牌”程序的代码复制到了我的CodeBlocks编辑器中,并试图运行它。它打开DOS框,一秒钟后我收到一条错误消息,提示“ filename.exe”已停止工作。
我已经检查了两次代码,没有任何错误。你们能帮我吗?
这是代码,以防万一:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>

struct card{
    const char *face;
    const char *suit;
};

typedef struct card Card;
void filldeck(Card * const wDeck, const char *wFace[],const char *wSuit[]);
void shuffle(Card * const wDeck);
void deal(const Card * const wDeck);

int main(void){
    Card deck[52];
    const char *face[]={"Ace","Deuce","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"};
    const char *suit[]={"Hearts","Diamonds","Clubs","Spades"};
    srand(time(NULL));

    fillDeck(deck,face,suit);
    shuffle(deck);
    deal(deck);
    return 0;
}

void fillDeck(Card * const wDeck, const char *wFace[],const char *wSuit){
    int i;
    for(i=0;i<=5;i++){
        wDeck[i].face=wFace[i%13];
        wDeck[i].suit=wSuit[i/13];
    }
}

void shuffle(Card * const wDeck){
    int i,j;
    Card temp;
    for(i=0;i<=5;i++){
        j=rand()%52;
        temp=wDeck[i];
        wDeck[i]=wDeck[j];
        wDeck[j]=temp;
    }
}

void deal(const Card * const wDeck){
    int i;
    for(i=0;i<=5;i++){
        printf("%5s of %-8s%s",wDeck[i].face,wDeck[i].suit,(i+1)%4 ? " ": "\n");
    }
}

最佳答案

您初始化前6张卡,然后在所有52张卡中随机播放,这意味着您要打印出一些未初始化的卡。 Your shuffle应为:

int n = 6;
for (i = n - 1; i >= 1; i--) {
    j = rand() % (i + 1);
    temp = wDeck[i];
    wDeck[i] = wDeck[j];
    wDeck[j] = temp;
}


您在fillDeck的定义中也有错字,缺少[],应为:

void fillDeck(Card * const wDeck, const char *wFace[], const char *wSuit[])


编译器不会将其视为错误,因为fillDeck的声明具有不同的字母大小写(filldeck)。

只初始化6张卡并不是一个好主意。您应该初始化整个卡组,然后从卡组中当前剩余的卡中随机抽出您要处理的卡。

关于c++ - filename.exe已停止在CodeBlocks中工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36532056/

10-11 15:56