【问题标题】:C Programming: Error in program. Won't show Max/Min/Average of files inputted by userC 编程:程序错误。不会显示用户输入的文件的最大/最小/平均值
【发布时间】:2015-07-30 19:57:24
【问题描述】:

我正在尝试创建用户输入文件名的代码,然后程序将找到文件中数字的最小值、最大值和平均值。

这是用户将输入到程序中的文件示例(# 是 cmets,将被忽略):

#Data from field experiment 312A
#2015-01-12
35.6
3.75
#2015-01-13
9
#2015-01-14
43.43
7.0001

这就是我目前的代码,我尝试结合不同的方法,但担心我现在太迷失了。

#include <stdio.h>
#include <math.h>

int main()
{
  char ch, file_name[25];
  FILE *fp;
  double average, num = 0, min = 0, max = 0, sum = 0, N;
  int i;

  printf("Please enter the name of the file to load:\n");
  scanf(file_name);

  fp = fopen(file_name, "r");

  if (fscanf(fp, "%lf", &N) == 1)
    {
      for (i = 0; i < N; i++)
      if (num < min || i == 0)
        min = num;
      if (num > max || i == 0)
        max = num;
      sum += num;
    }

  fclose(fp);
  average = sum/N;

  printf("Smallest: %7.2lf\n", min);
  printf("Largest: %7.2lf\n", max);
  printf("Average: %7.2lf\n", average);
  return(0);
}

任何帮助将不胜感激。

【问题讨论】:

  • 你应该提出一个明确的问题;什么不起作用,你得到什么输出,你期望什么。使代码最小化并且可以工作......
  • 你使用调试器了吗?应该会很快给你所有你需要的答案。
  • 代码符合要求,运行时我可以输入文件名,但随后收到分段错误(核心转储)错误。

标签: c file-io scanf


【解决方案1】:

在您的代码中,

  scanf(file_name);

scanf()使用错误,您缺少格式说明符。您必须将其更改为

  scanf("%24s", file_name);    //%s  is the format specifier for a string input

查看man page了解更多详情。

除此之外,您的程序中还有逻辑错误。您只读取一次文件,这不是您想要的。此外,for() 循环没有任何意义。

我的建议是:

  1. 打开文件,然后检查foepn()是否成功。否则,不要继续。
  2. 使用fgets()读取整行。
  3. 使用strtod()将输入字符串转换为float
  4. 如果转换成功,则检查&lt; min&gt; max,进行相应的更改,并将结果相加。
  5. 否则,如果转换失败,则为注释,忽略该行。
  6. 继续直到fgets() 返回NULL(每个文件结尾)
  7. 根据sum / (number of successful conversions)计算平均值
  8. 打印summaxmin
  9. 关闭文件。

也就是说,main() 的推荐签名是int main(void)


编辑:

一个伪代码(根据要求以便更好地理解)

#include <stdio.h>
#include <math.h>
#include <float.h>


int main(void)
{
char file_name[25] = {0};
FILE *fp = NULL;;
double average = 0, min = DBL_MAX, max = 0, sum = 0;
int N = 0;
char buf[128] = {0}; // buffer tyo be used with fgets()

ask for the filename  (using `scanf("%24s", file_name);`)

open the file (using `fp = fopen(file_name, "r");`)

    if file cannot be opened successfully (`if (!fp)`)
          exit

while (reading a complete line from file using `fgets(buf, 128, fp)` != EOF)  //EOF ==> end of file
{
    if (buf[0] ==  `#`)  //comment, no propcessing reqd, continue
        continue;

    val = strtod(buf, NULL);  //you should use proper error checking, as metioned in the man page

    if (val)  // valid float value found
    {
        if ( val < min )
            min = val;
        else if ( val > max )
            max = val;

        sum += val;   //add the value
        N++;          //increase the counter
    }
}

close the file (using `fclose(fp);`)
calculate `average = sum/N;`

  printf("Smallest: %7.2f\n", min);
  printf("Largest: %7.2f\n", max);
  printf("Average: %7.2f\n", average);
  return(0);
}

【讨论】:

  • 并忽略以#开头的注释行
  • @MarioTheSpoon 我认为这会导致strtod()失败,不是吗?
  • 是的,提前知道的时候避免出错是我的风格。
  • @SouravGhosh 根据您的建议,我不清楚如何实施它。任何澄清都会很棒。
  • @iamriotus 一步一步来,不要试图一次全部抓取。您在哪一步(在 1-9 中)遇到问题?您可以先阅读链接的手册页。
【解决方案2】:

你应该用一个很大的数字初始化min

您的if 需要{} 否则代码执行的方式与您想象的不同。

在计算sum/N 之前,您应该检查N&gt;0

fscanffor 的组合不能以这种方式工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多