Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับจำนวนสัตว์ในสวนสัตว์จากจำนวนหัวและขาใน C++


ให้จำนวนหัวและขาทั้งหมดในสวนสัตว์ งานคือคำนวณจำนวนสัตว์ โดยพิจารณาเฉพาะกวางและนกกา

อินพุต − heads = 60 legs = 200

เอาต์พุต − Count of deers are: 40 Count of peacocks are: 20

คำอธิบาย − ให้ x = จำนวนกวาง, y = จำนวนนกกา สมการ: x + y = 60, 4x + 2y = 200 แก้ได้ y = 20, x = 40

อินพุต − heads = 80 Legs = 200

เอาต์พุต − Count of deers are: 20 Count of peacocks are: 60

แนวทาง

  • รับจำนวนหัวและขา

  • คำนวณจำนวนกวาง = (legs - 2*heads)/2

  • จำนวนนกกา = heads - deers

ตัวอย่าง

#include <bits/stdc++.h> 
using namespace std; 

int count(int heads, int legs){ 
    int count = 0; 
    count = ((legs) - 2 * (heads)) / 2; 
    return count; 
} 

int main(){ 
    int heads = 80, 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