gpt4 book ai didi

c - 如何从文件中读取数字并将其分配给它们的实际含义

转载 作者:行者123 更新时间:2023-11-30 21:39:48 25 4
gpt4 key购买 nike

编写一个C程序

  1. 计算安大略省一系列湖滩的大肠杆菌平均水平
  2. 决定开放或关闭海滩
  3. 为数据文件中包含的所有湖泊和海滩生成报告。

对于每个海滩,文件中都有一行数据,其中以下字段以空格分隔 - 湖泊 ID(整数)、海滩编号(整数)、采样数(整数)和每个实数( double )采样代表100ml水中的生物数量。

湖表

1: Ontario        
2: Erie
3: Huron
4: Muskoka
5: Simcoe

沙滩 table

100: Kew Beach       
101: Sunnyside Beach
103: Sandbanks
201: Port Dover
202: Port Burwell
203: Crystal Beach
301: Goderich
302: Sauble Beach
303: Kincardine
401: Muskoka Beach
501: Sibbald Point

这是文件数据:

1 100 12 47.7 52.2 45.5 78.7 45.5 33.2 50.4 60.2 48.9 43.3 49.9 50.6     
1 101 9 75.5 53.2 65.1 81.1 44.1 42.2 41.1 39.7 51.1
2 201 3 56.6 49.7 45.5
2 202 2 44.4 66.6
5 501 4 55.5 34.4 66.6 22.2
4 401 4 33.3 44.4 55.5 66.6
3 301 3 50.0 51.1 49.8
3 302 4 77.7 66.6 22.2 33.3
3 303 3 55.5 55.5 44.0
1 103 1 13.3

我知道如何编写代码、语句,但我不知道如何使程序读取文件以及如何分配该特定数字是安大略湖,或者如何让程序对样本进行平均,我第一次编程才两个月,所以请耐心等待。

最佳答案

您可以在文件中写入 block 结构,以二进制形式保存数据。

对于创建结构

struct Lake_table {
int id;
char name[length];
};

struct Beach_table {
int samplings;
char name[length]
double samplings_ml;

};

用数据初始化结构!

struct Lake_table lakes[] =  {
{1,"Ontario"}
{2,"Erie"}
{3,"Huron"}
{4,"Muskoka"}
{5,"Simcoe"}
};

struct Beach_table beaches[] = {
{100,"Kew Beach",0.0}
{101,"Sunnyside Beach",0.0}
{103,"Sandbanks",0.0}
{201,"Port Dover",0.0}
{202,"Port Burwell",0.0}
{203,"Crystal Beach",0.0}
{301,"Goderich",0.0}
{302,"Sauble Beach",0.0}
{303,"Kincardine",0.0}
{401,"Muskoka Beach",0.0}
{501,"Sibbald Point",0.0}
};

要保存你的结构,就这样做!

FILE *file;
const char file_name[] = "filename.dat";
file = fopen(file_name,"wb");
if (file != EOF) {
fwrite(beaches,sizeof(struct Beach_table),length,file);

}

为了让你的结构做到这一点!

struct Beach_table beaches;
FILE *file;
const char file_name[] = "filename.dat";
file = fopen(file_name,"rb");
if (file != EOF) {
fread(beaches,sizeof(struct Beach_table),length,file);
}

访问数据,概念与数组、指针相同。祝你好运

关于c - 如何从文件中读取数字并将其分配给它们的实际含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28521859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com