用 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
廣告