c - 在 C 中的用户定义函数中将文本文件中的数字读取到数组

标签 c arrays file-io user-defined-functions

我在扫描文本文件中的值时遇到问题,我以前从未真正使用过文件 i/o,而且我对用户定义的函数仍然很不稳定,所以我几乎肯定错误是在第一个功能,我不知道如何修复它,但是,我在编程方面还很陌生,所以请耐心等待。

到目前为止我的代码是

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

int read_temps(void)
{
    int i;
    int num;
    int fileArray[25];

    FILE *file;
    file=fopen("temperatures.txt", "r");

    if (file == NULL)
    {
        printf("Error Reading File\n");
        exit(0);
    }
    for (i=0; i<25; i++)
    {
    fscanf(file,"%d", &fileArray[i]);
    }

    fclose(file);
    return fileArray[i];

}


int calc_results (int a[], int n)
{
    int i, j, maximum, minimum, average,sum;
    float avg;

printf ("Temperature conditions on October 26th, 2015:\n");
 printf("Time  Temperature in Degrees F \n");

   for(i = 0; i<25;i++)
    {
    printf("%d\t%d\n", i, a[i]);

        if(maximum < a[i])
            maximum = a[i];
        if(minimum > a[i])
            minimum = a[i];

            sum+=a[i];
    }

    printf("Maximum Temperature for the day: %d\n", maximum);
    printf("Minimum Temperature for the day: %d\n", minimum);

    avg=(float)sum/25;
    printf("Average Temperature for the day: %f\n", avg);

    return 0;
}


int main ()
{
    int average,i;

    int temp[25];
        for (i=0;i<25;i++)
        temp[i]= read_temps(); //calling user function for file input

calc_results(temp,i); //calling user function

return 0;
}

程序应该在 read_temps 中读取 .txt 文件中的值,计算 calc_results 中的最大值、最小值和平均值。它完成了所有这些工作并进行了编译,但它没有正确读取值。 .txt 文件包含 87、65、92 等数字,当我运行程序时,输出与 19863578 一样大,几乎对所有值重复,除了最大值、最小值和平均值。我不知道该怎么办:(

这些是文本文件上的值

    67
    67
    69
    71
    77
    79
    80
    80
    82
    85
    87
    88
    91
    93
    94
    95
    95
    96
    94
    90
    85
    82
    81
    77
    74

输出应该是

    Temperature Conditions on October 9, 2015: 
    Time of Day     Temperature in degrees F 
    0               85
    1               80
    2               97
    3               90
    4               73
    ........
    25              68

最佳答案

您的代码中的一个错误是您正在调用

for (i=0;i<25;i++)
temp[i]= read_temps();

在你的main函数中。并表演

for (i=0; i<25; i++)
    {
    fscanf(file,"%d", &fileArray[i]);
    }

在您的 read_temps 函数中,该函数将始终迭代 25 次,并始终返回文件中最后一个整数之后的垃圾值。

关于c - 在 C 中的用户定义函数中将文本文件中的数字读取到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33397604/

相关文章:

c# - WebClient异常,不支持并发I/O操作

arrays - C 指针数组与其他指针数组的元素

ruby - Ruby Array#[]= 预分配数组的线程安全吗?这可以无锁吗?

c++ - 在 C 中的 fwrite 上检测光盘移除

c - 什么是有符号整数溢出?

java - Arduino - Serial.read() 无法读取两位数数据?

java - BufferedReader 第二次使用返回 null

c - Go 系统调用 vs. C 系统调用

c - 如何在 C 中的枚举中声明字符串

c - 父子之间的双向管道通信