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

หาขนาดของสามเหลี่ยมมุมฉากจาก Hypotenuse และ Area ใน C++

ในปัญหานี้ เราได้รับ Hypotenuse (H) และ Area (A) ของสามเหลี่ยมมุมฉาก งานคือหาฐาน (base) และสูง (height)

สูตรทางคณิตศาสตร์

ให้ b = base, h = height (perpendicular)

  • Area: A = ½ × b × h → b×h = 2A
  • Pythagoras: H² = b² + h²

แก้สมการระบบ:

(b + h)² = b² + h² + 2bh = H² + 4A
(b - h)² = b² + h² - 2bh = H² - 4A

b + h = √(H² + 4A)
b - h = √(H² - 4A)  (ต้องมี H² ≥ 4A)

b = ½[√(H² + 4A) + √(H² - 4A)]
h = ½[√(H² + 4A) - √(H² - 4A)]

ตัวอย่าง

Input: H = 7, A = 8 Output: height = 2.44, base = 6.56

ตัวอย่างโค้ด

#include <iostream>
#include <cmath>
using namespace std;

void findDimensions(int H, int A) {
    if (H * H < 4 * A) { cout << "Not Possible"; return; }
    
    double sum = sqrt(H * H + 4.0 * A);
    double diff = sqrt(H * H - 4.0 * A);
    
    double base = (sum + diff) / 2.0;
    double height = (sum - diff) / 2.0;
    
    cout << "Base = " << base << ", Height = " << height;
}

int main() {
    findDimensions(7, 8);
    return 0;
}

ผลลัพธ์

Base = 6.56155, Height = 2.43845