这是我写的一个求线性相关直线的程序,运行后输入第一个x值后就没反应了。大家帮忙看看问题出在哪。附件里有源程序。
xiexie
/*----this is a program about linear regression-----------------------------*/
#include <stdio.h>
#include <math.h>
#define k 500 /* points number limitation */
void work();
void caculate(double point_x[],double point_y[],int p);
void main()
{
int p;
do
{
work();
puts ( " To continue,please press 1;to quit,please press 0" );
scanf ( "%d",&p );
}
while ( p==1 );
}
/*---------------------------------------------------------------------------*/
/* it's work() function dealing with input-------------------------------------*/
void
work()
{
double point_x[k];
double point_y[k];
int p; /* to control loop */
int fin=1; /* to judge if all the points have been scaned */
printf ( " please input all the points one by one,make sure the number"
" of the points is less than %d ",k);
for ( p=0 ; p<k ; p++ ) /* input points */
{
while ( fin == 1 )
{
printf ( "please input the x of %dth point x= \n",p+1);
scanf ( " %lg " , & point_x[ p ] );
printf ( " please input the y of %dth point y= \n",p+1);
scanf ( " %lg ", & point_y [ p ] );
fin = 0;
puts ( "input 1 to continue,or any key else to quit input." );
scanf (" %d ", & fin );
}
if ( fin == 0 ) break;
}
if( p == k ) puts ( "you have inputed too many points,we have to stop here.");
caculate( point_x , point_y , p );
}
/*---------------------------------------------------------------------------*/
/*--------------to caculate--------------------------------------------------*/
void
caculate ( double point_x[],double point_y[],int p )
{
double sum_x=0;
double sum_y=0;
double x_mean, y_mean;
double sum_xy=0,sum_xx=0,sum_yy=0;
int i; /* loop counter */
double slope;
double inter;
double r; /* mease the correlation coefficient */
for ( i=0 ;i < p ; i++ )
{
sum_x += point_x[i];
sum_y += point_y[i];
}
x_mean = sum_x / p;
y_mean = sum_y / p ;
for ( i = 0 ;i < p ;i++ )
{
sum_xy += ( ( point_x[i] - x_mean ) * ( point_y[i] - y_mean ) );
sum_xx += ( ( point_x[i] - x_mean ) * ( point_x[i] - x_mean ) );
sum_yy += ( ( point_y[i] - y_mean ) * ( point_y[i] - y_mean ) );
}
r = sum_xy / sqrt (sum_xx * sum_yy );
if ( r-0.9)
{
slope = sum_xy / sum_xx;
inter = y_mean - slope * x_mean ;
printf ( "the required straight line is: y = %g*x + %g .", slope,inter);
}
}