Question about logical operators

Asked

Viewed 1,954 times

4

I would like to know what the resolution of the following question is:

In a paddock, there are several ducks and rabbits. Write a program that asks the user for total heads and total feet and determine how many ducks and rabbits are in this enclosure.

I’ve tried everything I can and I can’t solve this problem.

  • 3

    In a quick google search, I found several answers to this problem. If you have already implemented could put the code to analyze.

2 answers

2

Come to logic, for every 1 head there are 2 or 4 legs.

2 legs = duck.
4 legs = rabbit.

The numbers should hit, for example, it makes no sense to have 10 heads and 200 feet, after all 10x4 = 40, this being the maximum possible of paws per head. There is also the minimum possibility, as 10 heads can have 20 legs. The two possibilities being true you can continue your program, missing implement more things, but would say this is a principle, you need to limit the possibilities to be within your goals.

I did in C a basic test, the logic in any language is the same:

int main(int argc, char** argv) {

    int totalCabecas;
    int totalPatas;

    printf("Digite o Total de Cabeças: ");
    scanf("%d", &totalCabecas);
    printf("Digite o Total de Patas: ");
    scanf("%d", &totalPatas);

    int testeMax = (totalCabecas) * 4; // 10x4 = 40, maximo de patas possiveis
    int testeMin = (totalCabecas) * 2; // 10x2 = 20, minimo de patas possiveis

    if ((totalPatas > testeMax) || (totalPatas < testeMin)) {
        printf("ERRO\n");
    } else {
        printf("OK!\nPossibilidade aceita\n");
    }

    return (EXIT_SUCCESS);
}

2

Designating, respectively, the numPatos, numCoelhos, numPes and numCabecas the numbers of ducks, rabbits, feet and heads, it is easy to see that

2*numPatos + 4*numCoelhos = numPes

and that

numPatos + numCoelhos = numCabecas.

Solving this system of linear equations, we will arrive at the following solution:

numPatos   =  2*numCabecas-numPes/2
numCoelhos =   -numCabecas+numPes/2

Now just implement the solution found:

#include <iostream>
using namespace std;

int main(){

    unsigned int numPatos, numCoelhos, numPes, numCabecas;

    cout << "Numero de pes: ";
    cin >> numPes;
    cout << "Numero de cabecas: ";
    cin >> numCabecas;

    numPatos   = 2*numCabecas-numPes/2;
    numCoelhos = -numCabecas+numPes/2;

    cout << endl
         << "Tem na sua cerca " << numPatos << " pato(s) e " << numCoelhos << " coelho(s).";

    return 0;

}

Browser other questions tagged

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