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

ความต่างสัมบูรณ์ระหว่างผลรวมและผลคูณของรากสมการดีกรี 4

ในส่วนนี้เราจะดูวิธาหาความต่างสัมบูรณ์ระหว่างผลรวมของราก และผลคูณของราก ของสมการดีกรี 4 (Quartic Equation)

สมการดีกรี 4: ax⁴ + bx³ + cx² + dx + e

แทนที่จะแก้สมการหาค่าราก แล้วค่อยหาผลรวมและผลคูณ (ซึ่งใช้เวลานาน) เราสามารถใช้สูตรได้เลย: ผลรวมราก = -b/a, ผลคูณราก = e/a ดังนั้นต้องหาแค่ |(-b/a) - (e/a)|

อัลกอริทึม

rootSumProdDiff(a, b, c, d, e)

begin
    sum := -b/a
    prod := e/a
    return |sum - prod|
end

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

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

double rootSumProdDiff(double a, double b, double c, double d, double e) {
    double sum = double(-b/a);
    double prod = double(e/a);
    return abs(sum - prod);
}

int main() {
    double a, b, c, d, e;
    cout << "Enter a, b, c, d, e for equation ax^4 + bx^3 + cx^2 + dx + e: ";
    cin >> a >> b >> c >> d >> e;
    cout << "Difference between sum and product of roots are: " << rootSumProdDiff(a, b, c, d, e);
}

ผลลัพธ์

Enter a, b, c, d, e for equation ax^4 + bx^3 + cx^2 + dx + e: 8 4 6 4 1
Difference between sum and product of roots are: 0.625