17、/*冒泡排序,从小到大,排序后结果输出到屏幕及文件myf2.out*/
#include<stdio.h>
void fun(int a[],int n)
{int i,j,t;
for(i=0;i<=n-1;i++)
for(j=0;j<i;j++)
if(a[j]>a[j+1]) {t=a[j];a[j]=a[j+1];a[j+1]=t;}
}
main()
{int a[10]={12,45,7,8,96,4,10,48,2,46},n=10,i;
FILE *f;
if((f=fopen("myf2.out","w"))==NULL)
printf("open file myf2.out failed!\n");
fun(a,10);
for(i=0;i<10;i++)
{printf("%4d",a[i]);
fprintf(f,"%4d",a[i]);
}
fclose(f);
}
18、编写函数countpi,利用公式
2 1 1121231234 3353573579
计算π的近似值,当某一项的值小于10-5时,认为达到精度要求,请完善函数。将结果显示在屏幕上并输出到文件p7_3.out中。
#include<stdio.h>
double countpi(double eps) /*eps为允许误差*/
{
int m=1;
double temp=1.0,s=0;
while(temp>=eps)
{ s+=temp;
temp=temp*m/(2*m+1);
m++;
}
return(2*s);
}
main()
{FILE *fp;
double eps=1e-5,pi;
if((fp=fopen("p7_3.out","w"))==NULL)
{ printf("cannot open the file\n");
exit(0);
}