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