📄 twomul.cpp
字号:
#include <stdio.h>
#include <malloc.h>
#include <math.h>
#include<conio.h>
struct dot
{
float x;
float y;
};
typedef struct dot DOT;
int getnumber(void);
void getdata(DOT *ptrdot,int count);
void displaydata(DOT *ptrdot,int count);
void twomul(DOT *ptrdot,int count,float *k,float *b,float *r);
void main()
{
float k=0.0,b=0.0,r=0.0;
int N=0;
char sel='q';
DOT *ptrdot;
printf("////////////////////////////////////////////////////////////////////////////////");
do
{
N=getnumber();
ptrdot=(DOT *)malloc(N*sizeof(DOT));
if(ptrdot==NULL)
{
printf("memory in short! press any key to end...");
getch();
}
getdata(ptrdot,N);
displaydata(ptrdot,N);
twomul(ptrdot,N,&k,&b,&r);
printf("\nk = %-8.6f\tb = %-8.6f\tr = %-8.6f\n",k,b,r);
printf("press q/Q to exit,else to continue...");
free(ptrdot);
sel=getch();
printf("\n///////////////////////////////////////////////////////////////////////////////\n");
}while((sel!='q')&&(sel!='Q'));
}
int getnumber(void)
{
int n=0;
printf("please input count of valuable dots: ");
do
{
scanf("%d",&n);
n=(int)n;
if(n<2){printf("count too small! please retry...");}
if(n>100){printf("count too large! please retry...");}
}while(n<2 || n>100);
return n;
}
void getdata(DOT *ptrdot,int count)
{
float tempx=0.0,tempy=0.0;
int i=0;
printf("\ninput dot: X Y\n");
while(i<count)
{
printf("please input dot %d :",i+1);
scanf("%f%f",&tempx,&tempy);
(ptrdot+i)->x = tempx;
(ptrdot+i)->y = tempy;
i++;
};
}
void displaydata(DOT *ptrdot,int count)
{
int i=0;
printf("\ndata you have input:\n");
while(i<count)
{
printf("dot%d:(%f,%f)\n",i+1,(ptrdot+i)->x,(ptrdot+i)->y);
i++;
};
printf("\n");
}
void twomul(DOT *ptrdot,int count,float *k,float *b,float *r)
{
float tempx=0.0,tempy=0.0;
float ave_x=0.0,ave_y=0.0,ave_xy=0.0,ave_x2=0.0,ave_y2=0.0;
int i=0;
while(i<count)
{
tempx=(ptrdot + i)->x;
tempy=(ptrdot + i)->y;
ave_x += tempx;
ave_y += tempy;
ave_xy +=(tempx*tempy);
ave_x2 +=(pow(tempx,2));
ave_y2 +=(pow(tempy,2));
i++;
};
ave_x /= count;
ave_y /= count;
ave_xy /= count;
ave_x2 /= count;
ave_y2 /= count;
printf("ave_x = %-8.6f\tave_y = %-8.6f\nave_x2 = %-8.6f\tave_y2 = %-8.6f\nave_xy = %-8.6f\n",ave_x,ave_y,ave_x2,ave_y2,ave_xy);
*k=(ave_x * ave_y - ave_xy)/(ave_x * ave_x - ave_x2);
*b=ave_y - (*k)*ave_x;
*r=(ave_xy - ave_x * ave_y)/(sqrt((ave_x2 -pow(ave_x,2))*(ave_y2 - pow(ave_y,2))));
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -