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

พื้นที่สามเหลี่ยมภายในสี่เหลี่ยมขนานใน C++

ปัญหา

ให้สี่เหลี่ยมขนานที่มีฐาน (base) และความสูง (height) มีสามเหลี่ยมล้อมรอบอยู่ภายใน โดยแบ่งปันฐานและความสูงเดียวกัน หาพื้นที่ของสามเหลี่ยม

สูตร

พื้นที่สามเหลี่ยม = ½ × ฐาน × ความสูง

Area = 0.5 * b * h

เหตุผล

สี่เหลี่ยมขนานพื้นที่ = b × h
สามเหลี่ยมที่มีฐานและความสูงเท่ากัน จะมีพื้นที่เป็นครึ่งหนึ่งของสี่เหลี่ยมขนานเสมอ

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

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

double triangleAreaInParallelogram(double base, double height) {
    return 0.5 * base * height;
}

int main() {
    double b = 30.0;
    double h = 22.0;
    double area = triangleAreaInParallelogram(b, h);
    
    cout << fixed << setprecision(2);
    cout << "Area of triangle with base " << b 
         << " and height " << h 
         << " is " << area << endl;
    
    // ทดสอบเพิ่มเติม
    cout << "Base=10, Height=5 → Area = " << triangleAreaInParallelogram(10, 5) << endl;
    cout << "Base=7.5, Height=4.2 → Area = " << triangleAreaInParallelogram(7.5, 4.2) << endl;
    
    return 0;
}

ผลลัพธ์

Area of triangle with base 30.00 and height 22.00 is 330.00
Base=10, Height=5 → Area = 25.00
Base=7.5, Height=4.2 → Area = 15.75

การประยุกต์ใช้

  • คำนวณพื้นที่ที่ดินรูปสามเหลี่ยม
  • Computer graphics: การคำนวณพื้นที่ polygon
  • Physics: คำนวณ work done โดย force triangle