C語言必背18個經典程式

2021-10-02 22:16:18 字數 2849 閱讀 3794

1、/*輸出9*9口訣。共9行9列,i控制行,j控制列。*/

#include "stdio.h"

main()

if(leap) /*內迴圈結束後,leap依然為1,則m是素數*/

for(i=2;i<=5;i++)

for(j=1;j<=i-1;j++)

a[i][j]=a[i-1][j]+a[i-1][j-1];

for(i=0;i<=5;i++)

7、/*通過鍵盤輸入3名學生4門課程的成績,

分別求每個學生的平均成績和每門課程的平均成績。

要求所有成績均放入乙個4行5列的陣列中,輸入時同一人資料間用空格,不同人用回車

其中最後一列和最後一行分別放每個學生的平均成績、每門課程的平均成績及班級總平均分。*/

#include

#include

main()

printf("%s\n",c);

指標法:

void invert(char *s)

main()

printf("input str:\n");

gets(str);

printf(「\n%s」,str);

fprintf(fp,「%s」,str);

invert(str);

printf(「\n%s」,str);

fprintf(fp,「\n%s」,str);

fclose(fp);

9、/*下面程式的功能是從字元陣列s中刪除存放在c中的字元。*/

#include

main()

system("pause");

fclose(fp);

11、已知陣列a中的元素已按由小到大順序排列,以下程式的功能是將輸入的乙個數插入陣列a中,插入後,陣列a中的元素仍然由小到大順序排列*/

main()

; /*a[0]為工作單元,從a[1]開始存放資料*/

int x , i, j=6; /*j為元素個數*/

printf("enter a number: ");

scanf("%d",&x);

a[0]=x;

i=j; /*從最後乙個單元開始*/

while(a[i]>x)

/*將比x大的數往後移動乙個位置*/

a[++i]=x;

j++; /*插入x後元素總個數增加*/

for(i=1;i<=j;i++) printf("%8d",a[i]);

printf("\n");

12、/*編寫函式replace(char *s,char c1,char c2)實現將s所指向的字串中所有字元c1用c2替換,字串、字元c1和c2均在主函式中輸入,將原始字串和替換後的字串顯示在螢幕上,並輸出到檔案p10_2.out中*/

#include

replace(char *s,char c1,char c2)

printf("enter a string:\n");

gets(str);

printf("enter a&&b:\n");

scanf("%c,%c",&a,&b);

printf("%s\n",str);

fprintf(fp,"%s\n",str);

replace(str,a,b);

printf("the new string is----%s\n",str);

fprintf(fp,"the new string is----%s\n",str);

fclose(fp);

13、/*在乙個字串s1中查詢一子串s2,若存在則返回子串在主串中的起始位置

,不存在則返回-1。*/

main()

stu[5]=,,,,};

main()

while(p!=null);

16、/*輸入乙個字串,判斷其是否為回文。回文字串是指從左到右讀和從右到左讀完全相同的字串。*/

#include

#include

#include

main()

main()

,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,利用公式

計算π的近似值,當某一項的值小於10-5時,認為達到精度要求,請完善函式。將結果顯示在螢幕上並輸出到檔案p7_3.out中。

#include

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

C語言必背18個經典程式

c語言必背 18個經典程式 1 輸出 9 9口訣。共9行 9列,i控制行,j控制列。include stdio.h main if leap 內迴圈結束後,leap 依然為1,則m 是素數 for i 2 i 5 i for j 1 j i 1 j a i j a i 1 j a i 1 j 1 f...

C語言必背18個經典程式

include stdio.h main if leap 內迴圈結束後,leap依然為1,則m是素數 for i 2 i 5 i for j 1 j i 1 j a i j a i 1 j a i 1 j 1 for i 0 i 5 i include include main printf s n...

c語言必背18個經典程式

1 輸出9 9口訣。共9行9列,i控制行,j控制列。include stdio.h main printf n 每一行後換行 2 古典問題 有一對兔子,從出生後第3個月起每個月都生一對兔子,小兔子長到第三個月後每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數為多少?兔子的規律為數列1,1,2,...