简体   繁体   English

在循环范围外使用局部变量

[英]Using local variables out of loop scope

I've got a function to calculate the total value of any given cards, it stores the sum of all current cards into score. 我有一个函数可以计算任何给定牌的总值,它将所有当前牌的总和存储到得分中。 It also counts the number of aces in the deck. 它还可以计算出牌组中的A数。 I'm having trouble linking the value of ace and score after the loop. 循环后,我无法将ace的值与得分联系起来。 I've implemented print statements in my actual file, it calculates correctly, but score and ace are obviously filled with random numbers after the for loop. 我已经在我的实际文件中实现了打印语句,它可以正确计算,但是在for循环之后,score和ace显然填充有随机数。 I don't know how to use those values outside of the for loop. 我不知道如何在for循环之外使用这些值。

    void calculateScore(Player * current_player)
    {
        int i, ace;
        unsigned score;
        ace = 0;
            score = 0;

        for (i=0; i<current_player->curnumcards; i++){
            if (current_player->hand[i].c_face == 0){
                ace++;
            } else if (current_player->hand[i].c_face == 10){
                score += 10;
            } else if (current_player->hand[i].c_face == 11){
                score += 10;
            } else if (current_player->hand[i].c_face == 12){
                score += 10;
            } else {
                score += ++current_player->hand[i].c_face;
            }//end if to check ace/jack/queen/king  

        }//end for loop

        if (ace>0){
            for (;ace!=1;ace--){

                if (score>11){
                    score += 1;
                } else {
                    score += 11;
                }//end if > 10 ace
            }//end for loop to calculate ace's
        }// end if ace loop 

        printf("Current score: %d\n", &score);

    }

you should printf("Current score %u\\n", score); 您应该printf(“当前分数%u \\ n”,分数); You are printing the memory address &score, where you just want score. 您正在打印内存地址和分数,您只想在其中评分。 And it's unsigned so %u not %i. 而且它是未签名的,所以%u不是%i。

ace, score = 0;

Takes the value of ace , does nothing with it, and assigns 0 to score . ace的值,不执行任何操作,并将0赋给score You probably want to assign 0 to both: 您可能要为两个都分配0:

ace = score = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM