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

โปรแกรม C++ หาสองจำนวนที่ผลรวมและผลคูณเท่ากับ N เดียวกัน


หา a, b ที่ทำให้ a+b = N และ a×b = N พร้อมกัน

กำจัด a ได้สมการกำลังสองใน b: b² - bN + N = 0

ใช้สูตรกำลังสองหาค่าราก:

a = (N - √(N² - 4N)) / 2
b = (N + √(N² - 4N)) / 2

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

#include <iostream>
#include <math.h>
using namespace std;

int main() {
    float N = 12, a, b;
    // cin >> N;
    a = (N + sqrt(N*N - 4*N))/2;
    b = (N - sqrt(N*N - 4*N))/2;
    cout << "The two integers are :" << endl;
    cout << "a - " << a << endl;
    cout << "b - " << b << endl;
    return 0;
}

ผลลัพธ์

The two integers are :
a - 10.899
b - 1.10102