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

ฟังก์ชัน acos() ใน C++ STL - หา Arc Cosine (อาร์กโคไซน์)

acos(x) คืนค่า อาร์กโคไซน์ (Inverse Cosine) ของ x ในหน่วย เรเดียน (radians) ช่วงค่าคือ 0 ถึง π

Syntax

double acos(double x);
float acos(float x);
long double acos(long double x);

Domain (โดเมน): x ∈ [-1, 1]
Range (เรนจ์): [0, π] เรเดียน (0° ถึง 180°)

ตัวอย่างโค้ดพื้นฐาน

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

int main() {
    double d = 0.75;
    double ans = acos(d);
    
    cout << "acos(" << d << ") = " << ans << " radians" << endl;
    return 0;
}

ผลลัพธ์

acos(0.75) = 0.722734 radians

แปลงเป็นองศา

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

int main() {
    double d = 0.75;
    double ans = acos(d);
    double degrees = ans * 180 / M_PI;
    
    cout << "acos(" << d << ") = " << degrees << " degrees" << endl;
    return 0;
}

ผลลัพธ์

acos(0.75) = 41.4096 degrees

ค่าสำคัญที่ควรจำ

x acos(x) radians acos(x) degrees
100°
0.5π/3 ≈ 1.04760°
0π/2 ≈ 1.57190°
-0.52π/3 ≈ 2.094120°
-1π ≈ 3.142180°

กรณีผิดพลาด (Domain Error)

double x = 1.5;
double result = acos(x);  // NaN (Not a Number) - นอกโดเมน
// errno จะถูกตั้งค่าเป็น EDOM

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

  • คำนวณมุมในสามเหลี่ยมจากความยาวด้าน (Law of Cosines)
  • กราฟิกส์ 3D - คำนวณมุมระหว่างเวกเตอร์
  • ฟิสิกส์ - มุมแทรก/สะท้อนแสง
  • Robotics - Inverse Kinematics

ตัวอย่าง: หามุมระหว่าง 2 เวกเตอร์

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

double angleBetweenVectors(double x1, double y1, double x2, double y2) {
    double dot = x1*x2 + y1*y2;
    double mag1 = sqrt(x1*x1 + y1*y1);
    double mag2 = sqrt(x2*x2 + y2*y2);
    double cosTheta = dot / (mag1 * mag2);
    return acos(cosTheta);  // คืนค่าเป็นเรเดียน
}

int main() {
    double angle = angleBetweenVectors(1, 0, 0, 1);  // 90°
    cout << "Angle: " << angle * 180 / M_PI << " degrees";
    return 0;
}