Error in calculating values of a vector

3

I'm stopped at this part of my job in college case 2, the output gets all mixed up, for example:

  

Profit will be -1,#$%#!@

#define vetor 40

struct Produto{
    char codigo[10];
    char descricao[100];
    float precoCompra;
    float precoVenda;
    int quantEstoque;
};

int main(){

    // Declaração das variaveis
    struct Produto estoque[vetor];

    float lucro;
    float lucro2;

    int opcao;
    int opcao2;
    int count;
    int i;

   // Inicios do menu do programa
   system("cls");  // Limpa a tela

    puts( "Escolha uma opção:" );
    puts( "1 - Cadastrar produto." );
    puts( "2 - Lucro da venda de todos os produtos." );
    scanf( "%d", &opcao );  // Lê a entrada do usuário

    fflush(stdin);  // Limpa o lixo da memoria
    system("cls");  // Limpa a tela

    // Inicios do switch case
    switch( opcao ){

        case 1:

            count = 1;

            system("cls");

            printf( "Deseja cadastrar um produto?\n1 - SIM\n2 - NAO\n" );
            scanf( "%d", &opcao2 );

            system("cls");

            while( opcao2 != 2 ){

                fflush(stdin);

                printf( "Entre com o codigo do produto: " );
                scanf( "%s", &estoque[count].codigo );

                printf( "Entre com a descricao do produto: " );
                scanf( "%s", &estoque[count].descricao );

               printf( "Entre com o preco da compra: " );
               scanf( "%f", &estoque[count].precoCompra );

                printf( "Entre com o preco da venda: " );
                scanf( "%f", &estoque[count].precoVenda );

                printf( "Entre com a quantidade em estoque:" );
                scanf( "%d", &estoque[count].quantEstoque );

                count++;

                system("cls");

                printf( "Deseja cadastrar outro produto?\n1 - SIM\n2 - NAO\n" );
                scanf( "%d", &opcao2 );

            }
            return main();

        case 2:

            lucro = 0;

            printf( "Lucro total com a venda de cada produto.\n" );

            for( i = 1; i <= vetor; i++ ){

                    fflush(stdin);

                    lucro = lucro + ( estoque[i].precoVenda * estoque[i].quantEstoque      );
                }

            fflush(stdin);

            printf( "O lucro sera de: %.2f", lucro );

            getch();
            return main();

    }


    return 0;
}

How can I resolve this?

    
asked by anonymous 28.08.2014 / 21:29

1 answer

1

Problem 1

You are calculating values with memory garbage.

In C, all vectors are indexed from 0 to N-1 , N being the number of elements in the vector.

In your case, the estoque vector has vetor positions. In your looping, you are initializing i with 1 and walking to i <= vetor . So when i == vetor , you will refer to uninitialized memory locations, which can cause random results (aka undefined behavior ) to segmentation failures ( access vilation if you use Windows, segmentation fault if you use almost anything else hehehe).

Solution

Change to your looping go from i = 0 to i < vetor .

In%% will also need to be fixed, since you use the case 1 variable to access the elements of count and it is being initialized with estoque value.

Problem 2

If you do not have all elements of the vector initialized (for example if the constant (I'm inferring since you did not post the statement) 1 value vetor but only insert 3 items in the 5 variable), you it will also read memory garbage in the estoque looping.

Solution

Keep a control variable (it may be the case 2 variable, but in global scope) with the number of elements in the count vector, and instead of traversing the estoque integer in estoque scroll only the% w of% first elements. It would be something like this:

for ( i = 0; i < count; i++ ) {
    // faça o cálculo aqui.
}

There are some other problems in the code, but at first these are the problems that are causing the errors found.

In addition, I am assuming first semester of the computer course, so I will not be boring and criticize all the problems at one time ...

I hope I have helped, Good luck!

    
28.08.2014 / 21:41