Logic error with MOD (%)

0

Good evening, I have a code that shows me wrong values, in my opinion, my logic is correct, but when I request results, what is shown has nothing to do with the ultimate goal 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 leases he would have for free. Every 10 Dvd's rented by him, he would have 1 free rental, that is, 54 rentals paid, 5 free rentals. The solution found by me was as follows:

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

But I always receive returns as above or below expectations. 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]);
        }
    }
}
    
asked by anonymous 19.11.2017 / 06:56

1 answer

0

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

Doing the operation

    varaux = vetorB[i] / 10;

varaux will receive the value of vectorB [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 percent symbol (%) you get 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 division has resulted 0 and rest 5).

If you want to know the number of free leases it would be wrong to put the second line, you just need to do the normal division 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 summary:

Just need to delete the line

        varaux = varaux % 10;
    
19.11.2017 / 07:56