c - 如何在c编程中找到atof函数中的数字总和
问题描述
- 代码必须读取文本文件
- 提取数字并找到它们的平均值
- 我已经提取了数字并将它们放在 ATOF 函数中
我的代码可以读取文件并提取数字,但我不知道如何找到提取的数字的总和并找到平均值。我在修改代码时需要帮助,因为我对 atof 函数不太熟悉
示例输入文本文件
LivingTemp1,17.8
LivingTemp2,17.9
LivingTemp1,18.1
LivingTemp2,18.2
LivingTemp1,18.5
LivingTemp2,18.6
LivingTemp1,19.0
LivingTemp2,19.0
LivingTemp1,19.5
LivingTemp2,19.6
LivingTemp1,20.0
LivingTemp2,20.1
LivingTemp1,20.6
LivingTemp2,20.6
LivingTemp1,19.8
LivingTemp2,19.8
LivingTemp1,19.4
LivingTemp2,19.5
LivingTemp1,19.0
LivingTemp2,19.1
LivingTemp1,18.5
LivingTemp2,18.6
LivingTemp1,18.0
LivingTemp2,18.1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
FILE *fp = fopen("test.txt", "r"); `opening the text file`
FILE *fp1 = fopen("test.txt", "r");
const char s[2] = ", ";
char *token;
char c;
int count = 1;
int i;
int number[24];
if(fp != NULL)
{
char line[24];
while(fgets(line, sizeof line, fp) != NULL)
{
token = strtok(line, s); // ignoring the commas
for(i=0;i<2;i++)
{
if(i==0)
{
//printf("%s\t",token);
token = strtok(NULL,s);
} else {
double num = atof(token);
printf("%.1f\n",num); // printing the extracted numbers
}
}
}
for (c = getc(fp1); c != EOF; c = getc(fp1)){
// countingthe number of lines the text file contains
if (c == '\n') // Increment count if this character is newline
count = count + 1;
}
printf("The file has %d lines\n ",count);
fclose(fp);
} else {
perror("test.txt");
}
}
解决方案
你的任务很简单:将每行的第二个标记转换为浮点数。如果转换成功,将该数字添加到总和并增加数据计数。最后,报告您的数据,但要注意除以零。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) // main returns int, not void
{
char line[80]; // make the line bige enough
int count = 0; // the count starts at zero, not at one
double sum = 0.0;
const char *filename = "test.txt";
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "Could not open '%s'.\n", filename);
exit(1);
}
while (fgets(line, sizeof line, fp)) {
const char *sep = ","; // don't include the space
char *token = strtok(line, sep);
if (token == NULL) continue; // skip empty lines
token = strtok(NULL, sep);
if (token) {
double T = atof(token);
if (T) {
sum += T;
count++;
}
}
}
fclose(fp);
if (count) {
printf("Number of measurements: %d\n", count);
printf("Average temperature: %g\n", sum / count);
} else {
puts("No data!");
}
return 0;
}
该函数atof
非常简单,如果无法转换数字,则返回 0.0。这意味着您无法区分实际数字 0(可能是摄氏度的温度)和转换失败。该功能strtod
为您提供更好的诊断。
推荐阅读
- pandas - 使用 Pandas 在每个 \newline 处将文本文件分成多个数据集
- javascript - 'number' 类型的参数不能使用 ParseInt 分配给'string' 类型的参数
- python - 匹配多个捕获组在正则表达式中必须不同的字符串
- javascript - 向 getRange() 添加变量
- ruby-on-rails - 即使满足条件,rails 6表单验证错误
- node.js - 如何使用 jest/enzyme 模拟 multer 以使用 axios post mock call 进行文件上传
- python - from ._nnls import nnls ImportError: DLL load failed: 找不到指定的模块
- bash - 使用 grep 完全匹配文件内文本中的字符串,然后将这些文件移动到单独的目录
- java - 如何使用 Spring Boot 和 Spring Data JPA 执行 Postgesql 全文搜索
- rest - Express JS - REST 身份验证和授权