C++程式查詢兩個數,使其和與積都等於N
在本教程中,我們將編寫一個程式來查詢兩個數,其中 x + y = n 且 x * y = n。有時無法找到此類數字。如果不存在此類數字,我們將列印**None**。讓我們開始吧。
給定的數字是二次方程的和與積。因此,如果 n2 - 4*n<0,則數字不存在。否則,數字將為$$\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
結論
如果您在本教程中有任何疑問,請在評論區中提出。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP