📜  从给定的头和腿数中计算动物园中的动物数

📅  最后修改于: 2021-05-06 21:29:11             🧑  作者: Mango

给定兔子和鸽子的腿和头的总数。任务是计算兔子和鸽子的数量。
例子:

Input: Heads = 200, Legs = 540 
Output: Rabbits = 70, Pigeons = 130

Input: Heads = 100, Legs = 300
Output: Rabbits = 50, Pigeons = 50

下面是上述方法的实现:

C++
// C++ implementation of above approach
#include 
using namespace std;
 
// Function that calculates Rabbits
int countRabbits(int Heads, int Legs)
{
    int count = 0;
 
    count = (Legs)-2 * (Heads);
    count = count / 2;
 
    return count;
}
 
// Driver code
int main()
{
    int Heads = 100, Legs = 300;
 
    int Rabbits = countRabbits(Heads, Legs);
 
    cout << "Rabbits = " << Rabbits << endl;
    cout << "Pigeons = " << Heads - Rabbits << endl;
 
    return 0;
}


Java
// Java implementation of above approach
import java.util.*;
import java.lang.*;
 
class GFG
{
// Function that calculates Rabbits
static int countRabbits(int Heads,
                        int Legs)
{
    int count = 0;
 
    count = (Legs) - 2 * (Heads);
    count = count / 2;
 
    return count;
}
 
// Driver code
public static void main(String args[])
{
    int Heads = 100, Legs = 300;
 
    int Rabbits = countRabbits(Heads, Legs);
 
    System.out.println("Rabbits = " +
                        Rabbits);
    System.out.println("Pigeons = " +
                      (Heads - Rabbits));
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


Python3
# Python 3 implementation of above approach
 
# Function that calculates Rabbits
def countRabbits(Heads, Legs):
    count = 0
 
    count = (Legs) - 2 * (Heads)
    count = count / 2
 
    return count
 
# Driver code
if __name__ == '__main__':
    Heads = 100
    Legs = 300
 
    Rabbits = countRabbits(Heads, Legs)
 
    print("Rabbits =", Rabbits)
    print("Pigeons =", Heads - Rabbits)
 
# This code is contributed
# by Surendra_Gangwar


C#
// C# implementation of above approach
using System;
 
class GFG
{
// Function that calculates Rabbits
static int countRabbits(int Heads,
                        int Legs)
{
    int count = 0;
 
    count = (Legs) - 2 * (Heads);
    count = count / 2;
 
    return count;
}
 
// Driver code
public static void Main()
{
    int Heads = 100, Legs = 300;
 
    int Rabbits = countRabbits(Heads, Legs);
 
    Console.WriteLine("Rabbits = " +
                       Rabbits);
    Console.WriteLine("Pigeons = " +
                     (Heads - Rabbits));
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


PHP


Javascript


输出:
Rabbits = 50
Pigeons = 50