C++ 程式查詢兩個數字之和與乘積都等於 N
本教程將討論一個程式,以找到兩個數字(比如“a”和“b”),使得兩者
a+b = N and a*b = N are satisfied.
從兩個等式中消除“a”,我們得到關於“b”和“N”的二次方程,即
b2 - bN + N = 0
這個等式將具有兩個根,這將為我們提供“a”和“b”的值。使用行列式方法求根,我們得到“a”和“b”的值為,
$a= (N-\sqrt{N*N-4N)}/2\ b= (N+\sqrt{N*N-4N)}/2 $
示例
#include <iostream>
//header file for the square root function
#include <math.h>
using namespace std;
int main() {
float N = 12,a,b;
cin >> N;
//using determinant method to find roots
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP