Error in the calculation of values of a vector

Asked

Viewed 96 times

3

I’m stuck in this part of my job in case two of college, the exit gets all jumbled up, for example:

The 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 fix this?

1 answer

1


Problem 1

You’re calculating values with memory junk.

In C, all vectors are indexed from the position 0 until the N-1, being N the quantity of vector elements.

In your case, the vector estoque possesses vetor positions. In your looping, you are initiating i with 1 and walking up to i <= vetor. Soon, when i == vetor, you will reference uninitialized memory positions, which may cause random results (aka undefined behavior) up to segmentation failures (access vilation if you use Windows, segmentation fault use almost anything else hehehe).

Solution

Switch to your looping go from i = 0 while i < vetor.

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

Problem 2

If you don’t have all the elements of the initialized vector (for example if the constant (I’m inferring since you didn’t post the statement) vetor be worth 5 but insert only 3 items into the variable estoque), you will also read memory junk in the case 2.

Solution

Keep a control variable (can be the variable itself count, but in global scope) with the amount of elements in the vector estoque, and instead of traversing the vector estoque whole in the case 2, just go through the count 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 found errors.

Also, I’m taking the first semester of the computer course, so I won’t be boring and criticize all the problems at once...

I hope I helped, Good luck!

Browser other questions tagged

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