必会的18个c语言入门经典程序

16 、 /* 输入一个字符串,判断其是否为回文。回文字符串是指从左到右读和从右到左读完全相同的字符串。 */



main()
{ char s[100];
int i,j,n;
printf(” 输入字符串: \n”);
gets(s);
n=strlen(s);

if(s[i]!=s[j]) break;
if(i>=j) printf(” 是回文串 \n”);
else printf(” 不是回文串 \n”);
}

17 、 /* 冒泡排序,从小到大,排序后结果输出到屏幕及文件 myf2 .out*/

void fun(int a[],int n)
{int i,j,t;

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);

{printf(“%4d”,a[i]);
fprintf(f,”%4d”,a[i]);
}
fclose(f);
}

18 、编写函数 countpi ,利用公式
⋯ + × × × + × × + × + + ≈
9
4
7
3
5
2
3
1
7
3
5
2
3
1
5
2
3
1
3
1
1
2
π
计算 π 的近似值 , 当某一项的值小于 10 -5
时 , 认为达到精度要求 , 请完善函数 。 将结果显示在屏幕上并输出到文件 p 7 _ 3 . out 中 。

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);
}
pi= countpi(eps);
printf(“pi=%lf\n”,pi);
fprintf(fp,”pi=%lf\n”,pi);
fclose(fp);
}

声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 智乐兔
转载请注明:转自《必会的18个c语言入门经典程序
本文地址:https://www.zhiletu.com/archives-2295.html
关注公众号:智乐兔

赞赏

wechat pay微信赞赏alipay pay支付宝赞赏

Pages: 1 2 3 4 5
上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!