ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมเพื่อค้นหาตัวเลขสองตัวโดยที่ x + y =n และ x * y =n บางครั้งก็ไม่สามารถหาตัวเลขประเภทเหล่านั้นได้ เราจะพิมพ์ ไม่มี หากไม่มีตัวเลขดังกล่าว มาเริ่มกันเลย
ตัวเลขที่ระบุเป็นผลรวมและผลิตภัณฑ์ของสมการกำลังสอง ดังนั้นหมายเลขนี้จะไม่มีอยู่ถ้า n 2 - 4*n<0.Else ตัวเลขจะเป็น $$\lgroup n + \sqrt n^{2} - 4*n\rgroup/2$$ และ $$\lgroup n - \sqrt n^{2} - 4*n\rgroup/2$$.
ตัวอย่าง
มาดูโค้ดกันเลย
#include <bits/stdc++.h>
using namespace std;
void findTwoNumbersWithSameSumAndProduc(double n) {
double imaginaryValue = n * n - 4.0 * n;
// checking for imaginary roots
if (imaginaryValue < 0) {
cout << "None";
return;
}
// printing the x and y
cout << (n + sqrt(imaginaryValue)) / 2.0 << endl;
cout << (n - sqrt(imaginaryValue)) / 2.0 << endl;
}
int main() {
double n = 50;
findTwoNumbersWithSameSumAndProduc(n);
return 0;
} ผลลัพธ์
หากคุณรันโปรแกรมข้างต้น คุณจะได้ผลลัพธ์ดังต่อไปนี้
48.9792 1.02084
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น