Logic error with MOD (%)

Asked

Viewed 219 times

0

Good evening guys, I’m with a code that shows me wrong values, in my view, my logic is correct but when I request result what is shown has nothing to do with the final objective of the code.

I have an activity that requests the name of the customer and the amount of dvd’s rented by him, based on the amount entered by the user the program must calculate how many rentals he would have free. For every 10 Dvds rented by him, he would have 1 free rental, that is, 54 paid rentals, 5 free rentals. The solution I found was as follows:

    aux = valor / 10; //54 / 10 = 5,4
    aux = aux % 10; //5,4 % 10 = 5

But always receive as return values above or below expected. Here’s my code below.

include

include

include

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

    int i, varaux;
    int vetorB[10];
    char vetorA[50][8];


    for(i = 0; i < 5; i++)
    {
        printf("Insira o nome completo do cliente, número [%i]: ", i+1);
        scanf("%s", &vetorA[i]);
    }

    printf("\n");

    for(i = 0; i < 5; i++)
    {
        printf("Insira a total de DVD's locados pelo cliente: %s ", vetorA[i]);
        scanf("%f", &vetorB[i]);
    }

    printf("\n");


    for(i = 0; i < 5; i++)
    {
        if(vetorB[i] > 10)
        {
            varaux = vetorB[i] / 10;
            varaux = varaux % 10;

            printf("O cliente %s possui um total de %i locações.\n", vetorA[i], varaux);
        }
        else
        {
            printf("O cliente não possui locações o suficiente. TOTAL: %i\n", vetorB[i]);
        }
    }
}

1 answer

0

In varaux you declared as integer, so it only stores an integer number.

Doing the operation

    varaux = vetorB[i] / 10;

varaux will receive the value of vector B[i] divided by 10 rounded down. In the case of your example:

    aux = valor / 10; // 54 / 10 == 5 (pois arredonda para baixo)

Doing the operation with the percentage symbol (%) you take the rest of the division

    aux = valor % 10; // 54 % 10 = 4 (pois 54 / 10 == 5 e tem resto 4)

The way you put it in the question above:

    varaux = vetorB[i] / 10;
    varaux = varaux % 10;

What’s happening is, you have 54 locations and divide by 10.

varaux = 54 / 10 (this gives 5)

then you ask the rest of the division for 10

varaux = 5 % 10 (which will also give 5, as the split has result 0 and rest 5).

If you want to know the number of free rentals would be wrong to put the second line, just need to do the normal breakdown by 10. Because if you put a value above 100, for example: 102 and run this code will happen the following:

    varaux = (102) / 10; // varaux == 10, porque despreza o resto
    varaux = (10) % 10; // varaux == 0, pois seria o resto da divisão de 10 / 10 

In short:

You just need to delete the line

        varaux = varaux % 10;

Browser other questions tagged

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