4- topshiriq
#include
#include
#include
float *a, *b, *x, *y, **sums;
int N, K;
//N - ma'lumotlar nuqtalari soni
//K - polinom kuchi
//K<=N
char filename[256];
FILE* InFile=NULL;
void count_num_lines()
{
//kirish faylidagi qatorlar sonini hisoblash - tenglamalar soni
int nelf=0; //bo'sh bo'lmagan bayroq
do
{
nelf = 0;
while(fgetc(InFile)!='\n' && !feof(InFile)) nelf=1;
if(nelf) N++;
}
while(!feof(InFile));
}
void freematrix()
{
//matritsalar uchun bepul xotira
int i;
for(i=0; i{
delete [] sums[i];
}
delete [] a;
delete [] b;
delete [] x;
delete [] y;
delete [] sums;
}
void allocmatrix()
{
//matritsalar uchun xotirani ajratish
int i,j,k;
a = new float[K+1];
b = new float[K+1];
x = new float[N];
y = new float[N];
sums = new float*[K+1];
if(x==NULL || y==NULL || a==NULL || sums==NULL)
{
printf("\nAjratish uchun xotira yetarli emas. N=%d, K=%d\n", N, K);
//exit(-1);
}
for(i=0; i{
sums[i] = new float[K+1];
if(sums[i]==NULL)
{
printf("\n%d ta tenglamani ajratish uchun xotira yetarli emas.\n", K+1);
}
}
for(i=0; i{
a[i]=0;
b[i]=0;
for(j=0; j{
sums[i][j] = 0;
}
}
for(k=0; k{
x[k]=0;
y[k]=0;
}
}
void readmatrix()
{
int i=0,j=0, k=0;
//kirish faylidan x, y matritsalarini o'qish
for(k=0; k{
fscanf(InFile, "%f", &x[k]);
fscanf(InFile, "%f", &y[k]);
}
//init kvadrat yig'indisi matritsasi
for(i=0; i{
for(j=0; j{
sums[i][j] = 0;
for(k=0; k{
sums[i][j] += pow(x[k], i+j);
}
}
}
//init bepul koeffitsientlar ustuni
for(i=0; i{
for(k=0; k{
b[i] += pow(x[k], i) * y[k];
}
}
}
void printresult()
{
//print polynom parameters
int i=0;
printf("\n");
for(i=0; i{
printf("a[%d] = %f\n", i, a[i]);
}
}
void diagonal()
{
int i, j, k;
float temp=0;
for(i=0; i{
if(sums[i][i]==0)
{
for(j=0; j{
if(j==i) continue;
if(sums[j][i] !=0 && sums[i][j]!=0)
{
for(k=0; k{
temp = sums[j][k];
sums[j][k] = sums[i][k];
sums[i][k] = temp;
}
temp = b[j];
b[j] = b[i];
b[i] = temp;
break;
}
}
}
}
}
void cls()
{
for(int i=0; i<25; i++) printf("\n");
}
int main()
{
int i=0,j=0, k=0;
cls();
do
{
printf("\nFayl nomini kiriting: ");
scanf("%s", filename);
InFile = fopen(filename, "rt");
}
while(InFile==NULL);
count_num_lines();
printf("\nBallar soni: N=%d", N);
do
{
printf("\nTaxminlovchi polinomning kirish quvvati Kscanf("%d", &K);
}
while(K>=N);
allocmatrix();
rewind(InFile);
//fayldan ma'lumotlarni o'qish
readmatrix();
//Asosiy diagonalda 0 bor yoki yo'qligini tekshiring va u holda qatorlarni almashtiring
diagonal();
fclose(InFile);
//printmatrix();
// qatorlarni qayta ishlash
for(k=0; k{
for(i=k+1; i{
if(sums[k][k]==0)
{
printf("\nYechim mavjud emas.\n");
return 0;
}
float M = sums[i][k] / sums[k][k];
for(j=k; j{
sums[i][j] -= M * sums[k][j];
}
b[i] -= M*b[k];
}
}
//printmatrix();
for(i=(K+1)-1; i>=0; i--)
{
float s = 0;
for(j = i; j{
s = s + sums[i][j]*a[j];
}
a[i] = (b[i] - s) / sums[i][i];
}
printresult();
freematrix();
}
Do'stlaringiz bilan baham: |