How to solve the C language chicken and rabbit in the s…

The problem of placing a chicken and a rabbit in the same cage is a classic math problem that can be solved using loops and exhaustive search.

If there are n chickens and m rabbits in a cage, there will be a total of x legs. According to the given conditions, each chicken has 2 legs and each rabbit has 4 legs, resulting in the equation:
2n + 4m = x

Based on this equation, we can solve the chicken and rabbit in the same cage problem using loops and exhaustive methods.
The specific steps are as follows:

  1. Input the total number of feet in the cage.
  2. Iterate through the values of 0 to x/2 for the number of chickens, n, because each chicken has two feet.
  3. Iterate from 0 to x/4 for the quantity of rabbits m, because each rabbit has four legs.
  4. In the loop, if the equation 2n + 4m equals x, then a solution has been found.
  5. Output the number of chickens as n and the number of rabbits as m.

Here is an example code written in C language:

#include <stdio.h>

int main() {
    int x;  // 总脚数
    printf("请输入笼子里的总脚数:");
    scanf("%d", &x);
    
    int n, m;
    int found = 0;  // 标记是否找到解
    
    for (n = 0; n <= x/2; n++) {
        for (m = 0; m <= x/4; m++) {
            if (2*n + 4*m == x) {
                found = 1;
                break;
            }
        }
        
        if (found) {
            break;
        }
    }
    
    if (found) {
        printf("鸡的数量:%d\n", n);
        printf("兔的数量:%d\n", m);
    } else {
        printf("无解\n");
    }
    
    return 0;
}

By running this code and inputting the total number of legs, you can obtain the solution for the number of chickens and rabbits.

bannerAds