c语言13,[作业] c语言13

博客内容涉及了C语言实现单向链表的创建、插入数据及显示,强调了内存管理。接着介绍了如何定义Person结构体,创建并初始化Person数组,将其存储到二进制文件中。最后,实现了一维数组的输入、保存到文本文件arr.txt,以及从文件加载并计算素数之和的功能,但存在数组第一个元素丢失的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

typedef struct list

{

int data;

struct list *next;

}List;

实现单向链表,添加一个数据,显示所有数据。注意内存泄露。

#include

#include

#include

typedef struct list{

int data;

struct list* next;

}List;

int main(void)

{

struct list* p1;

p1 = malloc(sizeof(struct list));

p1->data = 10;

p1->next = NULL;

p1->next = malloc(sizeof(struct list));

p1->next->data = 11;

p1->next->next = NULL;

p1->next->next = malloc(sizeof(struct list));

p1->next->next->data = 12;

p1->next->next->next = NULL;

struct list* current = p1;

for(; current != NULL; current = current->next)

printf("%d\n", current->data);

return 0;

}

定义结构体Person (包含: Id,名字,成绩);定义3个大小的Person结构体数组同时初始化(固定值)

实现将所有Person信息保存到二进制文件person.bin中。要求保存功能使用自定义函数实现(就是不要在main中直接调用fwrite,在自己定义的函数里面调用fwite实现)

#include

#include

#include

typedef struct Person{

int id;

char name[32];

int score;

}Stu;

void mysave(int* s, int m, int n)

{

FILE* fp1;

fp1 = fopen("person.bin", "wb");

fwrite(s, m, n, fp1);

fclose(fp1);

}

int main(void)

{

struct Person arr[3]={{10, "aaa", 98}, {11, "bbb", 96}, {12, "ccc", 97}};

int size = sizeof(struct Person);

mysave((int*)arr, size, 3);

struct Person temp[3];

FILE* fp2;

fp2 = fopen("person.bin", "rb");

fread(temp, sizeof(struct Person), 3, fp2);

for(int i = 0; i < 3; i++)

printf("%d %s %d\n", temp[i].id, temp[i].name, temp[i].score);

fclose(fp2);

return 0;

}

定义一维数组,从终端输入,并将数组保存为文本文件arr.txt,然后写加载函数,将arr.txt加载到程序中并求出所有素数的和并输出

#include

#include

#include

#include

int isPrime(int k)

{

if(k < 2) return 0;

for(int j = 2; j <= sqrt(k); j++)

if(k % j == 0)

return 0; //不为素数

return 1; //为素数

}

void myload(int* s)

{

FILE* fp2;

fp2 = fopen("person.bin", "rb");

fread(s, sizeof(s[10]), 1, fp2);//写入后读取第一个数保存为随机数,不知其原理

printf("#%d\n", s[0]);

fclose(fp2);

}

int main(void)

{

int a[10];

for(int i = 0; i < 10; i++)

scanf("%d", &a[i]);

FILE* fp1;

fp1 = fopen("arr.txt", "wb");

fwrite(a, sizeof(a), 1, fp1);

fclose(fp1);

printf("#%d\n", a[0]);

int size = sizeof(a[10]);

myload(a);

int sum = 0;

for(int s = 0; s < 10; s++)

if(isPrime(a[s]) == 1)

sum += a[s];

printf("%d\n", sum);//因该函数第一个数无法保存,计算存在误差

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值