用 C++ 统计动物园中动物的数量(已知头和腿的数量)
给定动物园中动物的头和腿的总数,任务是计算动物园中动物的总数。在下面的程序中,我们假设动物是鹿和孔雀。
输入 −
heads = 60 legs = 200
输出 −
Count of deers are: 40 Count of peacocks are: 20
解释 −
let total number of deers to be : x Let total number of peacocks to be : y As head can be only one so first equation will be : x + y = 60 And deers have 4 legs and peacock have 2 legs so second equation will be : 4x + 2y = 200 Solving equations then it will be: 4(60 - y) + 2y = 200 240 - 4y + 2y = 200 y = 20 (Total count of peacocks) x = 40(Total count of heads - total count of peacocks)
输入 −
heads = 80 Legs = 200
输出 −
Count of deers are: 20 Count of peacocks are: 60
解释 −
let total number of deers to be : x Let total number of peacocks to be : y As head can be only one so first equation will be : x + y = 80 And deers have 4 legs and peacock have 2 legs so second equation will be : 4x + 2y = 200 Solving equations then it will be: 4(80 - y) + 2y = 200 320 - 4y + 2y = 200 y = 60 (Total count of peacocks) x = 20(Total count of heads - total count of peacocks)
下面程序中使用的算法如下:
输入动物园中头和腿的总数。
创建一个函数来计算鹿的数量。
在函数内部,将鹿的数量设置为 ((腿)-2 * (头))/2
返回鹿的数量。
现在,通过从动物园中头的总数减去鹿的总数来计算孔雀的数量。
打印结果。
示例
#include <bits/stdc++.h> using namespace std; // Function that calculates count for deers int count(int heads, int legs){ int count = 0; count = ((legs)-2 * (heads))/2; return count; } int main(){ int heads = 80; int legs = 200; int deers = count(heads, legs); int peacocks = heads - deers; cout<<"Count of deers are: "<<deers<< endl; cout<<"Count of peacocks are: " <<peacocks<< endl; return 0; }
输出
如果运行以上代码,我们将得到以下输出:
Count of deers are: 20 Count of peacocks are: 60
广告