文章目录
第07页
题面如下:

题解如下:
D1043.c
原文件
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char ch;
/*********Found************/
if ((fp = fopen("Exam.txt", "r")) == NULL)
{
printf("can not open this file\n");
exit(0);
}
/*********Found************/
for( ; ch=getchar() == '@'; )
{
fputc(ch, fp);
}
fclose(fp);
return 0;
}
改后文件
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char ch;
/*********Found************/
if ((fp = fopen("Exam.txt", "w")) == NULL)
{
printf("can not open this file\n");
exit(0);
}
/*********Found************/
for( ; (ch=getchar()) != '@'; )
{
fputc(ch, fp);
}
fclose(fp);
return 0;
}
考查要点:
- 打开文件的模式要与功能需求一致,读用r,写用w
- ch=getchar()赋值完成以后再判断,注意运算的优先级
D1045.c
原文件
#include <stdio.h>
struct Student
{
char No[11];
int Score;
};
int FindMaxScore(struct Student stu[], int n);
int main(void)
{
struct Student stus[3] = {
{
"2008030201", 89}, {
"2008030202", 92}, {
"2008030203", 78}};
int k;
k = FindMaxScore(stus, 3);
printf("成绩最高的学生信息是:\n");
printf("学号\t\t成绩\n");
printf("%s\t%d\n", stus[k].No, stus[k].Score);
return 0;
}
/*********Found************/
int FindMaxScore(______________________)
{
int i, max, k=0;
max = stu[k].Score;
for (i=1; i<n; i++)
{
/*********Found************/
if (__________________)
{
k = i;
max = stu[k].Score;
}
}
return k;
}
改后文件
#include <stdio.h>
struct Student
{
char No[11];
int Score;
};
int FindMaxScore(struct Student stu[], int n);
int main(void)
{
struct Student stus[3] = {
{
"2008030201", 89}, {
"2008030202", 92}, {
"2008030203", 78}};
int k;
k = FindMaxScore(stus, 3);
printf("成绩最高的学生信息是:\n");
printf("学号\t\t成绩\n");
printf("%s\t%d\n", stus[k].No, stus[k].Score);
return 0;
}
/*********Found************/
int FindMaxScore(struct Student stu[], int n)
{
int i, max, k=0;
max = stu[k].Score;
for (i=1; i<n; i++)
{
/*********Found************/
if (max < stu[i].Score)
{
k = i;
max = stu[k].Score;
}
}
return k;
}
考查要点:
- 函数的参数:有数组时,一般都要将数组元素的个数也传入,方便对数据直接进行操作
- 函数的声明,定义实现,调用,头部分保持一致
- 这里使用的是打擂算法,要将数组里面的结构的对应成员值取出来比较【选取数组元素,取出来是一个结构,再打点取该元素对应的成员】
D1046.c
原文件
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
int ch;
/*********Found************/
fp = fopen("jsgc01.txt", "w");
if (NULL == fp)
{
printf( "Cannot open file!\n") ;
exit(1) ;
}
ch = fgetc(fp);
/*********Found************/
while (ch)
{
putchar(ch);
ch = fgetc(fp);
}
printf("\n");
fclose(fp);
return 0;
}
改后文件
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
int ch;
/*********Found************/
fp = fopen("jsgc01.txt", "r");
if (NULL == fp)
{

本文通过具体案例详细解析了C语言编程中常见的错误,并提供了正确的修改方案,涉及文件操作、结构体、指针等核心概念。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



