2

I am writing a program using C just to find the max and min numbers from my input file that contains about 500 floating numbers such as 54.54. I can get the program to run but the output says my min is 0 and my max is 54.88 which is the very first number from the file. Here is what i have so far.

#include <stdio.h>

int main(int argc, const char * argv[])
{

    FILE * fp;

    fp=fopen("file.txt","r");
    if (fp==NULL)
    {
        printf("Failed to open");
    }

    float i;
    float min ;
    float max ;

    {
        fscanf( fp, "%f", &i);

        if (i < min)
            min = i;
        if (i > max)
            max = i;
        }
    printf("Data range is: %f  %f \n", min, max);
    return 0;
}
4

5 回答 5

1

该计划将符合要求。

#include <stdio.h>

int main() 
{
    float num;
    float min = 999.99; /*Max value of number your file will not exceed*/
    float max = 0;
    int i = 0;

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

     while(fscanf(fp,"%f",&num) == 1)
     {
          if (num < min)
             min = num;
          if (num > max)
             max = num;
     }

    fclose(fp);

    printf("Data range is: %f  %f \n", min, max);

    return 0; 
}
于 2013-03-13T05:43:52.547 回答
1

最小值/最大值应初始化为适当的值。例如。

float inf = 1.0 / 0.0;  // also in math.h as INFINITY?
float max = -inf;
float min = inf;
float i;

另一种选择是将 min 和 max 初始化为从文件中读取的第一个值。这是编写循环的一种方法:

while (fscanf(fp, "%f", &i)==1)   // 
{
   ...
}
于 2013-03-13T05:37:18.200 回答
1

保留大部分代码:

#include <stdio.h>

int main(int argc, const char * argv[])
{
    float i=0, min=0, max=0;
    FILE * fp fp=fopen("file.txt","r");
    if (fp==NULL)
    {
        perror("Failed to open file.");
        return EXIT_FAILURE;
    }

    if (fscanf(fp,"%f", &i) == 1)
    {
        min = max = i;
        while (fscanf( fp, "%f", &i) == 1)
        {
            if (i < min)
                min = i;
            else if (i > max)
                max = i;
        }
    }

    printf("Data range is: %f  %f \n", min, max);
    return 0;
}

抱歉有任何错别字。

于 2013-03-13T06:05:57.270 回答
0

这是你可以做到的一种方法,如果你知道你将在每行上恰好有一个双精度数。它可能不是最优雅的,但在我脑海中编译它似乎可以完成工作。

(我没有对此代码进行错误测试,而且我不确定这是否是最大和最小双精度值的正确宏)

char buf[10]; /* as big as the biggest number */
char c;
int i = 0;
double d, dmax = -INFINITY, dmin = INFINITY;

while ((c = getc(fp)) != EOF) {
    if (c != '\n')
        buf[i++] = c;
    else {
        buf[i] = '\0';
        d = atof(buf);
        if (d > dmax) dmax = d;
        if (d < dmin) dmin = d;
        i = 0;
   }
}
于 2013-03-13T05:30:47.363 回答
0

您没有读取文件中所有数字的循环。你得到的只是第一个。

于 2013-03-13T04:59:34.593 回答