Coming out of the while loop

Asked

Viewed 42 times

-1

I’m making a program that would be a board game that when all 4 players reach the house 100 the program to, however my code is not stopping at the 100:

#include <locale.h>
#include <stdlib.h>
#include <time.h>



int main(){
 setlocale(LC_ALL, "");
 int i;
 int aux;
 int jogador[4] ={1,2,3,4};
 int pos[4] = {0,0,0,0};
 int volta[10];
 int avanca[10];
 srand(time(NULL));

 while(pos[i] != 100){     
   for(i = 0; i < 4; i++){
      aux= rand()%7;
      if(aux == 0){
        aux= rand()%7;
        pos[i] +=  aux;
        printf("\n\tJogador %d joga novamente\n", jogador[i] );
        printf("\njogador: %d -> jogada: %d -> posicao: %d \n", jogador[i], aux, pos[i]);
        } else {
            pos[i] +=  aux;
            printf("\njogador: %d -> jogada: %d -> posicao: %d \n", jogador[i], aux,pos[i]);
         }
      }
    }
 system("pause");
 return 0;
}```


1 answer

1

while condition test is incorrect:

while(pos[i] != 100)

It does not test all array positions and if any player has the position a value above 100 then it will also not stop in the loop because values above 100 are different from 100. The correct is to test each position and check if the value has already reached 100 or more.

I rewrote your code and included a role to check if any player has won after each round:

#include <locale.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <stdbool.h>

bool venceu(int pos[], int quantos) {
        int venceu = false;
        for (int i = 0;i < quantos;i++) 
                if (pos[i] >= 100)
                    venceu = true;
        return venceu;
}

int main(){
 setlocale(LC_ALL, "");
 int i = 0;
 int aux;
 int jogador[4] ={1,2,3,4};
 int pos[4] = {0,0,0,0};
 int volta[10];
 int avanca[10];
 srand(time(NULL));

 while(!venceu(pos, 4)) {     
    for(i = 0; i < 4; i++){
      aux= rand()%7;
      while(aux == 0){
        aux= rand()%7;
      }
      printf("\n\tJogador %d joga novamente\n", jogador[i] );
      pos[i] +=  aux;
      printf("\njogador: %d -> jogada: %d -> posicao: %d \n", jogador[i], aux,pos[i]);
      }
    }
 //system("pause");
 return 0;
}
  • Hello, but now the loop understands that every player must repeat the move. I built an architecture to make it easier to read what needs to be done but I’m having trouble stopping when all four players are in the 100 and to advance and return according to the position the player is in. I will send you the diagram I made: https://i.stack.Imgur.com/Ckgyd.png

Browser other questions tagged

You are not signed in. Login or sign up in order to post.