假设有一个单精度型数组a,共有10个元素,使用数组名表示元素的地址输入数组各元素,使用数组下标表示元素输出数组中包含的正数。
定义具有数据成员学号、姓名、性别及年龄的结构体。定义输入函数,其输入结构体变量的值;定义输出函数,其输出输出结构体变量的值;统计输入的结构体数组中所有成员的平均年龄和女生人数
建立一个文本文件“d:\ff\goodstudent.txt”,首先从键盘向该文件输入一系列字符,接着将文件中的内容显示到屏幕上,但把文件中的‘0’~‘9’数字字符,显示到屏幕上时用‘*’代替
ChatGPT尝试为您解答,仅供参考
1.单精度型数组输入输出
#include <stdio.h>
#define N 10
int main(void) {
// 定义单精度型数组
float a[N];
// 使用数组名表示元素的地址输入数组各元素
printf("Please enter %d float numbers:\n", N);
for (int i = 0; i < N; i++) {
scanf("%f", &a[i]);
}
// 使用数组下标表示元素输出数组中包含的正数
printf("The positive numbers in the array are:\n");
for (int i = 0; i < N; i++) {
if (a[i] > 0) {
printf("%f ", a[i]);
}
}
printf("\n");
return 0;
}
2.结构体输入输出
#include <stdio.h>
// 定义结构体
struct Student {
char id[20];
char name[20];
char gender[10];
int age;
};
// 定义输入函数,其输入结构体变量的值
void input_student(struct Student *s) {
printf("Please enter the student's id, name, gender and age:\n");
scanf("%s%s%s%d", s->id, s->name, s->gender, &s->age);
}
// 定义输出函数,其输出输出结构体变量的值
void output_student(struct Student s) {
printf("id: %s\n", s.id);
printf("name: %s\n", s.name);
printf("gender: %s\n", s.gender);
printf("age: %d\n", s.age);
}
int main(void) {
// 定义结构体数组
struct Student students[3];
// 输入结构体数组各元素
for (int i = 0; i < 3; i++) {
input_student(&students[i]);
}
// 输出结构体数组
for (int i = 0; i < 3; i++) {
output_student(students[i]);
}
// 统计输入的结构体数组中所有成员的平均年龄和女生人数
int total_age = 0;
int female_count = 0;
for (int i = 0; i < 3; i++) {
total_age += students[i].age;
if (students[i].gender[0] == 'F' || students[i].gender[0] == 'f') {
female_count++;
}
}
printf("Average age: %.2f\n", (float)total_age / 3);
printf("Female count: %d\n", female_count);
return 0;
}
3.文件读写
#include <stdio.h>
int main(void) {
// 建立文件句柄
FILE *fp;
// 以写入方式打开文件
fp = fopen("d:\\ff\\goodstudent.txt", "w");
if (fp == NULL) {
printf("Failed to open the file.\n");
return 1;
}
// 从键盘向文件输入一系列字符
printf("Please enter some characters:\n");
char c;
while ((c = getchar()) != '\n') {
fputc(c, fp);
}
// 关闭文件
fclose(fp);
// 以读取方式打开文件
fp = fopen("d:\\ff\\goodstudent.txt", "r");
if (fp == NULL) {
printf("Failed to open the file.\n");
return 1;
}
// 将文件中的内容显示到屏幕上
printf("The contents of the file are:\n");
while ((c = fgetc(fp)) != EOF) {
// 把文件中的'0'~'9'数字字符,显示到屏幕上时用'*'代替
if (c >= '0' && c <= '9') {
putchar('*');
} else {
putchar(c);
}
}
printf("\n");
// 关闭文件
fclose(fp);
return 0;
}