任务4:
源代码:
# include<stdio.h> int main() { FILE *p; char ch; int cnt_zf=0,cnt_hs=1; p=fopen("D:/democ.1/data4.txt","r"); if(!p) printf("fail to open"); while((ch=fgetc(p))!=EOF) { if(ch!=' '&&ch!='\n'&&ch!='\t') cnt_zf++; else if(ch=='\n') cnt_hs++; } fclose(p); printf("字符个数:%d\n",cnt_zf); printf("行数:%d\n",cnt_hs); return 0; }
运行结果:
任务五:
源代码:
# include<stdio.h> # include<string.h> # define N 10 typedef struct{ long id; char name[20]; float objective; float subjective; float sum; char result[10]; }STU; void read(STU st[],int n); void write(STU st[],int n); void output(STU st[],int n); int process(STU st[],int n,STU st_pass[]); int main(){ STU stu[N],stu_pass[N]; int cnt ; double pass_rate; printf("从文件中读入%d个考生信息...\n",N); read(stu,N); printf("\n对考生成绩进行统计....\n"); cnt=process(stu,N,stu_pass); printf("\n通过考试的名单:\n"); output(stu,N); write(stu_pass,cnt); pass_rate=1.0*cnt/N; printf("\n本次等级考试通过率:%.2f%%\n",pass_rate*100); return 0; } void read(STU st[],int n) { int i; FILE *fin; fin=fopen("D:\\实验7数据文件及部分代码\\实验7数据文件及部分代码\\examinee.txt","r"); if(!fin){ printf("fail to open"); return; } while(!feof(fin)) { for(i=0;i<n;i++) fscanf(fin,"%ld %s %f %f",&st[i].id,st[i].name,&st[i].objective,&st[i].subjective); } fclose(fin); } void output(STU st[],int n) { int i; printf("准考证号\t姓名\t客观题得分\t操作题得分\t总分\t\t结果\n"); for(i=0;i<n;i++) printf("%ld\t\t%s\t%.2f\t\t%.2f\t\t%.2f\t\t%s\n",st[i].id,st[i].name,st[i].objective,st[i].subjective,st[i].sum,st[i].result); } void write(STU st[],int n) { FILE *p; int i; p=fopen("list_pass.txt","w"); if(!p) { printf("fail to open"); return; } fprintf(p,"%s\t%s\t\t%-10s\t\t%s\t\t%s\t\t %10s\n","准考证号","姓名","客观题得分","操作题得分","总分","结果"); for(i=0;i<n;i++) fprintf(p,"%ld\t\t%-10s\t%.2f\t\t%.2f\t\t%.2f\t\t%-10s\n",st[i].id,st[i].name,st[i].objective,st[i].subjective,st[i].sum,st[i].result); fclose(p); } int process(STU st[],int n,STU st_pass[]) { int i,cnt=0; for(i=0;i<n;i++) { st[i].sum=st[i].objective+st[i].subjective; if(st[i].sum>=60) strcpy(st[i].result,"通过"),st_pass[cnt++]=st[i]; else strcpy(st[i].result,"不通过"); } return cnt; }
运行结果:
任务六:
源代码:
# include<stdio.h> # include<stdlib.h> # include<time.h> typedef struct{ long id; char name[80]; char class[80]; }STU; int main() { long wj=0; STU x[80]; int i,s[5],m,b=1,cnt=0; FILE *p; p=fopen("D:\\实验7数据文件及部分代码\\实验7数据文件及部分代码\\list.txt","r"); if(!p) { printf("fail to open"); return 1; } for(i=0;i<80;i++) fscanf(p,"%ld%s%s",&x[i].id,x[i].name,x[i].class); srand(time(NULL)); for(cnt=0;cnt!=5;){ m=rand()%80; for(i=0;i<cnt;i++) if(m==s[i]) b=-1; if(b!=-1) s[cnt++]=m,b=1; } for(i=0;i<5;i++) printf("%-30ld %-30s %-30s\n",x[s[i]].id,x[s[i]].name,x[s[i]].class); FILE *new; new=fopen("20241230.txt","w"); if(!new){ printf("fail to open"); return 1; } for(i=0;i<5;i++) fprintf(new,"%-30ld %-30s %-30s\n",x[s[i]].id,x[s[i]].name,x[s[i]].class); fclose(p); fclose(new); return 0; }
运行结果:
标签:cnt,int,pass,st,STU,实验,printf From: https://www.cnblogs.com/hshnbnb666/p/18639985