簡體   English   中英

C中的程序讀取txt文件=查找最小值,最大值,平均值

[英]program in C read txt file = find min, max, avg

我需要編寫一個程序來打開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 ;

}  ```

您正在逐字符讀取文件,這不是讀取數字的好方法。 如果文件包含數字“ 137”,您將讀為“ 1”,然后為“ 3”,然后為“ 7”。 它可以用於計數行,因為您只需要計算'\\ n'字符的數量即可。

文件中是否包含數字列表,每行一個數字? 如果是這樣,則應使用fgets讀取一行文件。 然后,您可以使用atoi將字符串轉換為整數並查找max,min等。您必須注意一個問題, fgets將把\\n存儲在它返回的字符串中,因此您可能需要去掉它。

如果您的文件包含以空格分隔的數字,則可以考慮使用fscanf ,這對於行也可以使用...? 由於我使用fscanf已經很久了,所以我對此不太確定。

僅因為它是課堂作業而提示,如果您自己動手做,您將成為更好的開發人員:-)

想法是掃描所有數字並記住最大和最小的數字。 對於平均值,您還需要累積所有這些數字的總和以及計數。

例如,考慮以下偽代碼:

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.

暫無
暫無

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

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