I can not do division with an element of vector

2

I made a code to simulate the Monty Hall paradox, so that I can simulate 1000 times the results and write the statistics. However, I can not divide an element from an 'array' of 'int' by an 'int', every time I run the program, when it arrives in the room, the program hangs and has to be closed:

void main(){
    int PORTAS [] = {0, 0, 0}; 
    int CAR, ESC, NUM, DECISAO, AUX;
    float VIT, DER; 
    int ESTAT [] = {0, 0, 0};   // {Tentativas, vitórias, derrotas}

    VIT = ( ESTAT[2] / NUM ) * 100; // Porcentagem de vitórias  *ERRO*
    DER = ( ESTAT[3] / NUM ) * 100; // Porcentagem de derrotas  *ERRO*
}

I also tried writing as:

VIT = ESTAT[2]/ESTAT[1]*100;
DER = ESTAT[3]/ESTAT[1]*100;

But in this way, the result always gives 0.

If necessary to help me, I will put the complete code, which includes at the beginning a brief explanation of the game. If you feel you do not need to ignore the code below:

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>

/*Paradoxo de Monty Hall
*Atrás de uma porta, de três no total, é escondido um carro
*e nas outras duas, uma cabra. No jogo, o jogador escolhe uma
*porta e então é revelada outra porta que contenha uma cabra.
*O jogador tem então a opção de escolher entre manter a escolha
*ou trocar de porta. Esse programa simula esse jogo, de modo que 
*a porta seja mantida ou trocada em todas as tentativas, para
*motivos estatísticos.*/

void main(){
    setlocale (LC_ALL, "");

    int PORTAS [] = {0, 0, 0};  // 0 - a porta contém uma cabra; 1 - a porta contém o carro 
    int CAR, ESC, NUM, DECISAO, AUX;
    float VIT, DER; 
    int ESTAT [] = {0, 0, 0};   // {Tentativas, vitórias, derrotas}

    printf("1 para trocar todas, 0 para manter todas: ");
    scanf ("%d", &DECISAO);
    printf ("Digite o número de repetições: "); // Recomendável 10, 100 ou 1000.
    scanf ("%d", &NUM);

    do{
        CAR = rand () %3;   // Randomiza a porta que recebe o carro.
        PORTAS [CAR] = 1;   

        ESC = rand () %3;   // Randomiza a escolha da porta.

        if ( DECISAO == 1 ){    // Se foi escolhido trocar todas as vezes.
            if ( PORTAS [ESC] == 1 ){   // Porta escolhida contém o carro.
                for ( AUX = 0; AUX < 3 ; AUX++ ){
                    if ( PORTAS [AUX] != 1 && AUX != ESC ){
                        ESC = AUX;      //Mudança de porta
                        AUX = 3;    // Para quebrar o 'For'
                        ESTAT [3] += 1;
                    }
                }
            }

            if ( PORTAS [ESC] == 0){    //Porta escolhida contém uma cabra.
                ESC = CAR;  // Pois sendo a porta errada, e tendo a outra errada sido revelada, só sobrou a correta.
                ESTAT [2] += 1;
            }
        }

        if ( DECISAO == 0){     //Caso tenha sido escolhido manter todas as vezes.
            if ( ESC = CAR ){
                ESTAT [2] += 1;
            }
            else{
                ESTAT [3] += 1;
            }
        }

        NUM--;
        ESTAT [1] += 1;
    } while ( NUM > 0);

    VIT = ( ESTAT[2] / NUM ) * 100; // Porcentagem de vitórias  *ERRO*
    DER = ( ESTAT[3] / NUM ) * 100; // Porcentagem de derrotas  *ERRO*

    ( DECISAO == 1 ) ? printf ("\n\n\n\tTrocando de porta todas as vezes: \n\n") : printf ("\n\n\n\tMantendo a porta todas as vezes: \n\n");
    printf ("Número de tentativas: %d\n", ESTAT [1]);
    printf ("Número de vitórias: %d, %d%% do total.\n", ESTAT [2], VIT);
    printf ("Número de derrotas: %d, %d%% do total.", ESTAT [3], DER);

    getch();
}
    
asked by anonymous 24.11.2015 / 23:01

2 answers

1

I do not know what the goal is but this is basic math. The code is running when NUM is 0 and this operation is not possible according to the math rule.

You probably should not use an array for this specific problem of the question, three variables would be more readable. This is just one of the things that makes the code difficult to read and understand. In addition, you are using elements 1, 2, and 3 when it should be 0, 1, and 2.

The second way may not cause the problem but is it what you want? You can not include random variables in the expression to see if it works. And this used is very random, does not make the slightest sense. You have to do what you need. And only you know it.

I think it should be like in the first form, but keeping the initial value of the variable. You can not reuse variables. I created a new variable called repeticoes to save the value and do the division correctly.

In fact the code is full of errors. It's no use trying to solve complex problems when you do not know the basics of programming. After solving several compilation errors it looks like it worked, but I do not guarantee you're doing what you want. So there must be problems that go beyond what is in the question.

See "working on ideone" .

    
24.11.2015 / 23:23
0
  

I also tried writing as:

VIT = ESTAT[2]/ESTAT[1]*100;
DER = ESTAT[3]/ESTAT[1]*100;

There are two problems here: first, in C the arrays are indexed from zero, not from one, so that the first element has index 0 , second index 1 , and third index 2 . Accessing the 3 index as you are doing is invalid for an array of 3 size, and the result is undefined (since you are accessing a region of arbitrary memory that may even be outside the scope of your program.)

The second problem is that the entire division will always give an integer result, even though the variable where you want to store the result is float . If the dividend is less than the divisor then the result will always be zero (as you have noted). Fixing both problems we have:

 VIT = 1.0f*ESTAT[1]/ESTAT[0]*100; // Ao multiplicar primeiro por 1.0f
 DER = 1.0f*ESTAT[2]/ESTAT[0]*100; // o operando passa a ser um float

Your very first one (as NUM ) was failing because you were decreasing NUM in your loop until you reached zero. When trying to divide by zero, of course there would be a problem ...

P.S. I did not review the full code - for bigown already did that - but after correcting the major mistakes we got to this end result (whose result corresponds to the expected, statistically speaking). Some recommendations:

  • Do not use variables with the whole name in uppercase, as this notation is traditionally used to represent constants only;
  • Document your variables, and try to give them self-descriptive names. I personally had no difficulty understanding what was CAR [ro] and ESC [look], but this is due to my previous knowledge of Monty Hall, other people may have more difficulty relating variables to elements of the domain;
  • If two conditions exclude each other, I suggest using else even if you do not think it is necessary. In this code:

        if ( PORTAS [ESC] == 1 ){   // Porta escolhida contém o carro.
           ...
        }
    
        if ( PORTAS [ESC] == 0){    //Porta escolhida contém uma cabra.
           ...
        }
    

    You did not use else , so it ended up entering the second if even after you entered the first one (because it changed ESC ) - making the number of hits plus the number of errors exceeded the number of attempts ...

    Two if s followed without else should only be used if there is a chance to enter: a) only in the first; b) only in the second; c) in both; d) in neither.

  • I saw that you tried to simulate the change of choice (reassigning ESC ), but in that case this is unnecessary - if he chose right, will lose, if he chose wrong, will win, anything. Anyway, your loop that uses AUX is correct, albeit a bit confusing (by the way, did you know you can exit earlier than a loop using break ?).

25.11.2015 / 02:24