Question about logical operators

4

I wanted to know the resolution of the following question:

  

In a pen, 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 how many rabbits are found in the enclosure.

I have tried everything and it has not solved this problem.

    
asked by anonymous 17.05.2015 / 06:06

2 answers

2

Let's go to logic, for every 1 head there are 2 or 4 legs.

  

2 legs = duck.   Home   4 legs = rabbit.

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

I made 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);
}
    
17.05.2015 / 07:54
2

Assigning the numbers of ducks, rabbits, feet and heads, by% with%,% with%,% with% and% with%

2*numPatos + 4*numCoelhos = numPes

and that

numPatos .

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;

}
    
13.12.2015 / 06:06