#include <stdio.h>
#include <stdlib.h>
#define E (0.000000001)
void Guass(double ** _matrix,double * result,int n)
{
int i,j,k;
double temp = 0.0;
for(i=0; i<n; i++)
{
for(j=i ; j<n ; j++)
{
for(k=i+1; k<=n; k++)
{
if(_matrix[j][i] > E || _matrix[j][i] < -E)
{
_matrix[j][k] /= _matrix[j][i];
}
if(j > i)
{
_matrix[j][k] -= _matrix[i][k];
}
}
}
}
//回代
for(i=n-1; i>=0 ; i--)
{
temp = 0.0;
for(j=n-1 ; j>i; j--)
{
temp += result[j] * _matrix[i][j];
}
result[i] = _matrix[i][n] - temp;
}
}
int main(void)
{
int i,j;
double temp,sum;
double result[5] = {0};
double ** matrix = (double **)malloc(sizeof(double *) * 5);
for(i=0 ; i<5 ; i++)
{
matrix[i] = (double *)malloc(sizeof(double) * (5 + 1));
sum = 1;
for(j=0; j<5 ; j++)
{
sum *= (i+1);
matrix[i][j] = sum;
}
}
// T={1,2,3,4,5}和S={12.1,32.4,45.3,36.7,78.9}
matrix[0][5] = 12.1;
matrix[1][5] = 32.4;
matrix[2][5] = 45.3;
matrix[3][5] = 36.7;
matrix[4][5] = 78.9;
Guass(matrix,result,5);
printf("f(x) = ");
temp = 1;
sum = 0;
for(i=0 ; i<5 ; i++)
{
temp *= 4.6;
sum += result[i] * temp;
if(i > 0)
{
if(result[i] > 0)
{
printf("+");
}
}
printf("%0.4lf*x^%d",result[i],i+1);
}
printf("\nf(4.6) = %lf\n",sum);
for(i=0 ; i<5 ; i++)
{
free(matrix[i]);
}
free(matrix);
return 0;
}
|