簡體   English   中英

如何在 c 編程中找到 atof function 中的數字總和

[英]How can i find the sum of numbers in atof function in c programming

  1. 代碼必須讀取文本文件
  2. 提取數字並找到它們的平均值
  3. 我已經提取了數字並將它們放在 ATOF function

我的代碼可以讀取文件並提取數字,但我不知道如何找到提取的數字的總和並找到平均值。 我在修改代碼時需要幫助,因為我對 atof function 不太熟悉

示例輸入文本文件

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;
}

function atof非常簡單,如果無法轉換數字,則返回 0.0。 這意味着您無法區分實際數字 0(可能是攝氏度的溫度)和轉換失敗。 function strtod為您提供更好的診斷。

這是一個更簡單的版本:

#include <err.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  int living, n, count=0;
  double value, sum = 0.0;

  FILE *fp = fopen("test.txt", "r"); //`opening the text file`
  if( !fp ) err(EXIT_FAILURE, "no input");

  while( (n = fscanf(fp, "LivingTemp%d,%lf ", &living, &value)) == 2 ) {
    count++;
    sum += value;
  }

  if( n != EOF ) {
    errx(EXIT_FAILURE, "failed to parse line %d", count);
  } 

  if( !feof(fp) ) {
    err(EXIT_FAILURE, "failed to read file");
  }

  printf( "average of %d values is %f\n", count, sum / count );

  return EXIT_SUCCESS;
}

只是為了笑,我還解析了“活着”的數字。 ISTM 在實際情況下,您需要按標識符計算平均值和計數。 如果您需要,該值將被解析出來。

通常我建議在掃描之前閱讀一行。 在您的情況下,您的輸入已明確指定,您可以直接掃描它。 請注意,這也補償了空白行,因為格式字符串以空格結尾。 它的缺點是在第一次失敗的解析時中止,而不是報告錯誤並繼續到文件結尾。

scanf (3) 函數通常被 IMO 低估。 一個 scanf 語句可以幫助您重新發明標記化、跳過空格和單獨轉換每個組件。 例如,請注意轉換失敗會顯示在轉換計數中(由函數返回)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM