在 C++ 程序中查找两个数字,其和与乘积都等于 N
c++server side programmingprogramming
在本教程中,我们将编写一个程序来查找两个数字,其中 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; // 检查虚根 if (imaginaryValue < 0) { cout << &"None";; return; } // 打印 x 和 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