【问题标题】:program in C read txt file = find min, max, avgC 中的程序读取 txt 文件 = 查找最小值、最大值、平均值
【发布时间】:2019-11-24 22:20:16
【问题描述】:

我需要编写一个程序,打开一个txt 文件并列出有多少个数字(例如下面有 25 个数字),然后列出哪个数字最大(最大)和哪个最小(最小) .然后程序对这些数字进行平均。

到目前为止,我的程序只写了我得到的数字。当我试图将公式发挥到最大时,我只是停下来不能动弹。

你能帮帮我吗?如何通过读取行​​并评估最大数字来做到这一点?

#include <stdio.h>

FILE *input;

int open()

{
    if ((input = fopen("data.txt", "r")) == NULL)
  {
      printf("Error! opening file");

      return 0;
  }
}

int rows_reading ()
//Here i dont know what to do

{

input = fopen ("data.txt", "r");

}

void main ()
{
  char c;
  int linesCount = 0;
  float max, min;

  float a;
  float n;
  int count = 0;

  input = fopen ("data.txt", "r");

  while ((c = fgetc(input)) !=EOF)
  {
      if(c =='\n')
          linesCount++;

       } // this works

  while ((c = getc(input)) !=EOF)
       {
           for (a = 0; a <  count; a++){
               if (a > max)
               max = a;

               }

       } //this not work

  printf("In file is %d numerical values. Max value is %d"linesCount, max);

  return ;

}  ```

【问题讨论】:

  • 我看不出有什么计数和 for 循环。无需多次读取值即可记住最大值! (也不是最小值,也不是求平均值)

标签: c


【解决方案1】:

提示只是因为它是课堂作业,如果你自己搞清楚你会成为一个更好的开发者:-)

这个想法是扫描所有数字并记住最大和最小的数字。对于平均值,您还需要将所有这些数字的总和与计数一起累加。

例如,考虑以下伪代码:

def getMinMaxAvg(inputFile):
    set sum, count, smallest, largest all to zero
    set value to inputFile.getNumber()
    if none available, return error indication
    while true
        if count is zero or value is less than smallest:
            set smallest to value
        if count is zero or value is greater than largest:
            set largest to value
        add value to sum
        add one to count
        set value to inputFile.getNumber()
        if none available, return (smallest, largest, sum / count)

这基本上就是您需要的流程。这里的第一件重要的事情是inputFile.getNumber(),它可以获取您的号码。您使用fgetc 将输入单个字符,您可能希望将fscanf"%d" 说明符一起使用,这样您就可以输入整数。

只需确保检查返回值以确保它正常工作:

int myInt; FILE *fileHandle = fopen(...);
if (fscanf(fileHandle, "%d", &myInt) != 1)
    // Did not scan properly, needs to be handled.
// Now, myInt contains your value.

【讨论】:

  • 非常感谢您的帮助。最后它工作了:)。
【解决方案2】:

您正在逐个字符地读取文件,这不是读取数字的好方法。如果文件包含数字“137”,您将读取“1”,然后是“3”,然后是“7”。它适用于计算行数,因为您可以只计算您正在执行的 '\n' 字符的数量。

文件是否包含数字列表,每行一个数字?如果是这样,您应该使用fgets 一次读取一行文件。然后您可以使用atoi 将字符串转换为整数并查找最大值、最小值等。您必须注意我们的一个问题,fgets 会将\n 存储在它返回的字符串中,所以你可能需要删除它。

如果您的文件包含由空格分隔的数字,那么您可能会考虑使用fscanf,它可能也适用于行...?不太确定,因为我使用fscanf 已经很久了。

【讨论】:

  • 谢谢!我没有意识到我正在逐个字符地读取文件。愚蠢的我。 fscanf 运行良好。
猜你喜欢
  • 2012-09-27
  • 2015-12-24
  • 2014-01-13
  • 2021-06-18
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
  • 1970-01-01
  • 2015-01-16
相关资源
最近更新 更多