为什么当我尝试打印数组的所有值时,这个 C 程序只打印一个 0?

问题描述 投票:0回答:1

我似乎无法弄清楚我做错了什么,以及为什么输出不包含存储在结构体数组中的所有 0。非常感谢任何帮助!!!

#include <stdio.h>
#include <string.h>
#include <time.h>

struct Player{
    int suitsInHand[4], facesInHand[13];
};

void emptyHands(struct Player *empty){
    for (int y = 0; y < 13; y++){
        empty->facesInHand[y] = 0;
    }
    for (int x = 0; x < 4; x++){
        empty->suitsInHand[x] = 0;
    }
}

void printHand(const struct Player *print){
    for (int x = 0; x < 13; x++){
        printf("%d ", print->facesInHand[x]);
        if(x = 12){
            printf("\n");   
        }
    }
    for (int y = 0; y < 4; y++){
        printf("%d ", print->suitsInHand[y]);
        if(y = 3){
            printf("\n");   
        }   
    }
}

int main(){
    srand(time(NULL));      
    struct Player playerOne;
    emptyHands(&playerOne);
    printHand(&playerOne);
    return 0;
}

我尝试过对数组使用不同形式的打印,但我需要它位于 main 之外的自己的函数中。

arrays c struct printf
1个回答
0
投票

当我复制你的代码然后编译它时,编译器发回了一些关于“printHand”函数中的“if”测试的警告。

||=== Build: Release in Cards (compiler: GNU GCC Compiler) ===|
/home/craig/C_Programs/Console/Cards/main.c||In function ‘printHand’:|
/home/craig/C_Programs/Console/Cards/main.c|27|warning: suggest parentheses around assignment used as truth value [-Wparentheses]|
/home/craig/C_Programs/Console/Cards/main.c|35|warning: suggest parentheses around assignment used as truth value [-Wparentheses]|
/home/craig/C_Programs/Console/Cards/main.c||In function ‘main’:|
/home/craig/C_Programs/Console/Cards/main.c|44|warning: implicit declaration of function ‘srand’ [-Wimplicit-function-declaration]|
||=== Build finished: 0 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|

以下是该函数的当前代码。

void printHand(const struct Player *print){
    for (int x = 0; x < 13; x++){
        printf("%d ", print->facesInHand[x]);
        if(x = 12){                             /* Suspect equality check  */
            printf("\n");   
        }
    }
    for (int y = 0; y < 4; y++){
        printf("%d ", print->suitsInHand[y]);
        if(y = 3){                              /* Suspect equality check  */
            printf("\n");   
        }   
    }
}

在这个重构的代码中,最有可能的那两行代码应该如下所示。

void printHand(const struct Player *print){
    for (int x = 0; x < 13; x++){
        printf("%d ", print->facesInHand[x]);
        if(x == 12){                                /* Refactored  */
            printf("\n");   
        }
    }
    for (int y = 0; y < 4; y++){
        printf("%d ", print->suitsInHand[y]);
        if(y == 3){                                 /* Refactored  */
            printf("\n");   
        }   
    }
}

重构这些位后,以下是终端的测试输出。

craig@Vera:~/C_Programs/Console/Cards/bin/Release$ ./Cards 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 

很明显,需要在代码中添加更多功能和测试,以便处理正确的牌值和花色组合。但最大的收获可能是在编译代码时认识到任何编译器警告。尽管它们是警告,但这些消息通常是即将出现不需要的程序行为的线索。

此外,参考有关“if”测试使用的其他教程可能是明智的。

© www.soinside.com 2019 - 2024. All rights reserved.