在C++中从n个方程组(缺失一个方程)中求解n个变量
在这个问题中,我们给定一个数组sum[],它包含(n-1)个变量的和,
Sum[1] = x2 + x3 + x4 + … xn Sum[2] = x1 + x3 + x4 + … xn . . Sum[i] = x2 + x3 + x4 + … x(i-1) + x(i+1) + … + xn . . Sum[n] = x1 + x2 + x3 + … x(n-1) Our task is to find the value of x1, x2,... xn.
让我们来看一个例子来理解这个问题,
输入
sum[] = {6, 6, 6, 6, 6, 6, 6}
输出
x1 = 1, x2 = 1, x3 = 1, x4 = 1, x5 = 1, x6 = 1, x7 = 1
解释
arr[1] = 1 + 1 + 1 + 1 + 1 + 1 = 6
解决方案方法
设所有变量的和为sumX,
sumX = x1 + x2 + x3 + … + xn
因此,sum数组的值为:
sum[1] = x2 + x3 + x4 + … xn = -x1 + x1 + x2 + x3 + x4 + … xn = sumX - x1
类似地,
sum[2] = sumX - x2 sum[3] = sumX - x3 . sum[i] = sumX - xi . sum[n] = sumX - xn
将所有sum数组加起来,我们得到:
Sum[1] + sum[2] + … sum[n] = sumX - x1 + sumX - x2 + … + sumX - xn arrSum = n*sumX - (x1 + x2 + x3 … xn) arrSum = n*SumX - (x1 + x2 + x3 … xn) arrSum = sumX*(n-1) sumX = arrSum/ (n-1)
使用这个sumX的值,我们可以找到x1, x2…的值。
所以,
x1 = sumX - sum[1] x2 = sumX - sum[2] .. xi = sumX - sum[i] .. xn = sumX - sum[n]
程序演示了我们的解决方案的工作原理,
示例
#include <iostream> using namespace std; void calcSumVariables(int sum[], int n) { float SUMX = 0; for (int i = 0; i < n; i++) { SUMX += sum[i]; } SUMX /= (n - 1); for (int i = 0; i < n; i++) cout<<"\nx"<<(i + 1)<<" = "<<(SUMX - sum[i]); } int main(){ int sum[] = {3, 8, 6, 7, 4, 5, 9 }; int N = sizeof(sum) / sizeof(sum[0]); cout<<"The value of variables that form the sum are "; calcSumVariables(sum, N); return 0; }
输出
构成和的变量的值是
x1 = 4 x2 = -1 x3 = 1 x4 = 0 x5 = 3 x6 = 2 x7 = -2
广告