While循环使用某些if语句获得超高数字

时间:2019-06-17 23:26:27

标签: c

我正在用C做边界游戏,而while循环和在输出中获取的值存在一些问题。

我有一个数组,其中有一些随机值,从-5 ti 5开始,占木板的20%。而我想做的就是将这个值添加到名为player的变量中。

int player1 = 0, player2 = 0, player3 = 0, player4 = 0;
int dice = 0, number_of_players = 0, number_of_players = 2;


while(player1 < 50 && player2 < 50){
    if(number_of_players == 2){
        dice = (rand() % 6) + 1;
        player1 += dice;
        if(border[player1] != 0){
            player1 = player1 + (border[player1]);
        }      
        dice = (rand() % 6) + 1;
        player2 += dice;      
        if(border[player2] != 0){
            player2 = player2 + (border[player2]);
        }      
    }   
}
if(player1 > player2) printf("Player 1 won. Score: %d", player1);
if(player2 > player1) printf("Player 2 won. Score: %d", player2);

这是我的数组“ border”的代码,它在我的while循环之上:

#define TAM 50

int border[TAM], i, pos, casas;
for( i=0; i<TAM; i++ )
    border[i] = 0;

i = 0;
while( i < (int)TAM*0.1 ){
    pos = rand() % TAM;
    if( border[pos] == 0 ){
        casas = (rand() % 5) + 1;
        border[pos] = casas;
        i++;
    }
}

i = 0;

while( i < (int)TAM*0.1 ){
    pos = rand() % TAM;
    if(border[pos] == 0){
        casas = (rand() % 5) + 1; 
        border[pos] = casas * (-1);
        i++;
    }
}

输出有时是50,我不知道结果如何,因为只有当玩家达到51或更高时它才会停止循环。我还获得了诸如299158477之类的超高值。 我是C的新手。谢谢大家。

1 个答案:

答案 0 :(得分:0)

  

int骰子= 0,玩家数 = 0,玩家数 = 2;

您的代码不应被编译,变量必须声明两次。


if(border[player1] != 0){
    player1 = player1 + (border[player1]);

您不需要if()。如果border为零,那么结果将不会改变。


i = 0;
while( i < (int)TAM*0.1 ){
    pos = rand() % TAM;
    if( border[pos] == 0 ){
        casas = (rand() % 5) + 1;
        border[pos] = casas;
        i++;
    }
}

while()应该是for()


while( i < (int)TAM*0.1 ){

应该是

while( i < (TAM/10) ){

casas = (rand() % 5) + 1;

也许应该是:

casas = (rand() % 6) + 1;

因为你有骰子?无论如何,对于代码的逻辑而言并没有那么重要。


player1变为> = TAM(在player1 += dice;之后)时,您访问border之外的内存

player1 = player1 + (border[player1]);