简体   繁体   English

用C语言编写代码以从文本文件中查找最大和最小数字

[英]Code in C to find largest and smallest numbers from text file

I am attempting to write a program that takes a user's inputted text file and returns the largest number, smallest number, average of the numbers and the standard deviation of the numbers. 我正在尝试编写一个程序,该程序采用用户输入的文本文件并返回最大数,最小数,数字的平均值和数字的标准差。 The text file that we input is formatted as such (with the first number being "N", or the total number of numbers, and the second row the list of all the numbers): 我们输入的文本文件是这样格式化的(第一个数字为“ N”或数字总数,第二行为所有数字的列表):

5

4.34 23.4 18.92 -78.3 17.9 4.34 23.4 18.92 -78.3 17.9

So far, this is my code 到目前为止,这是我的代码

int main(int argc, char*argv[])
{
    double average, num = 0, min = 0, max = 0, sum = 0, N, std_dev, sum_sqs;
    FILE * pFile;
    pFile = fopen("argv[1]", "r");
    fscanf(pFile, "%lf", &N);

    while(!feof(pFile))
    {
            fscanf(pFile, "%d", &num);
            if (num < min)
                    min = num;
            if (num > max)
                    max = num;
            sum += num;
            sum_sqs += (num*num);
    }
    average = sum/N;
    std_dev = sqrt((sum_sqs/N)-(average*average));

    printf("Smallest: %.2lf\n", min);
    printf("Largest: %.2lf\n", max);
    printf("Average: %.2lf\n)", average);
    printf("Standard deviation: %.3lf\n", std_dev);
return(0);
}

Currently, the compiler does not let me get past an error about an undefined reference to sqrt and i cannot figure out what's wrong. 当前,编译器不允许我忽略关于sqrt的未定义引用的错误,而且我无法弄清楚出了什么问题。 Thank you in advance to everybody who takes the time to respond! 预先感谢所有抽出宝贵时间回复的人! I really appreciate any help, I am still getting the hang of C. If my code is not doing what I intend it to do please dont hesitate to correct me! 我真的很感谢任何帮助,我仍然无法理解C。如果我的代码没有按照我的意图去做,请随时纠正我!

Updated the messy part to below. 将凌乱的部分更新到下面。 Still not sure what exactly im doing with the rest though haha pFile = fopen(argv[1], "r"); 仍然不确定我到底在做什么,尽管哈哈pFile = fopen(argv [1],“ r”); fscanf(pFile, "%lf", &N); fscanf(pFile,“%lf”,&N);

    if (fscanf(pFile, "%lf", &N) == 1)
    {
            for (int i = 0; i < N; i++)
            {
            if (fscanf(pFile, "%lf", &num) == 1)
                    if (num < min)
                            min = num;
                    if (num > max)
                            max = num;
                    sum += num;
                    sum_sqs += (num*num);
    }
    average = sum/N;
    std_dev = sqrt((sum_sqs/N)-(average*average));

Analysis 分析

There is a wealth of problems in these few lines: 以下几行中存在很多问题:

pFile = fopen("argv[1]", "r");
fscanf(pFile, "%lf", &N);

while(!feof(pFile))
{
        fscanf(pFile, "%d", &num);
  1. You probably wanted to open the file designated by argv[1] , not a file called argv[1] . 您可能想要打开argv[1]指定的文件,而不是打开名为argv[1]的文件。 Remove the quotes. 删除引号。
  2. You didn't check that you were passed an argument. 您没有检查自己是否通过了论证。
  3. You don't check that fopen() succeeded, so you probably crashed in your first fscanf() . 您无需检查fopen()成功,因此您可能在第一个fscanf()崩溃了。
  4. You don't check that fscanf() succeeded. 您无需检查fscanf()成功。 It is also odd to read what should probably be an integer value into a double , but the notation used will work. 将可能是整数的值读为double也是奇怪的,但是使用的表示法将起作用。
  5. You should not use feof() like that, especially if … 您不应该这样使用feof() ,尤其是在…
  6. You don't check that the second fscanf() succeeded, and it won't work properly (but might not report the problem) because … 您没有检查第二个fscanf()成功,并且它不能正常工作(但可能无法报告问题),因为…
  7. You are trying to read integers ( %d ) into a double . 您正在尝试将整数( %d )读入double

So, you should have written: 因此,您应该写出:

if (argc <= 1)
    …report error and exit…(or use pFile = stdin)…
FILE *pFile = fopen(argv[1], "r");
if (pFile == 0)
    …report error and exit…
if (fscanf(pFile, "%lf", &N) == 1)
{
    for (int i = 0; i < N; i++)
    {
        if (fscanf(pFile, "%lF", &num) != 1)
            …report error, close file, and exit…
        …as before…more or less…subject to fixing any as yet undiagnosed errors…
    }
}
fclose(pFile);

Incidentally, you forgot to set sum_sqs to zero before you started adding to it, so you won't know what value you got. 顺便说一句,您在开始添加之前忘记将sum_sqs设置为零,因此您将不知道获得什么值。 Also, if all the numbers are negative, you'll report that the maximum is 0; 另外,如果所有数字均为负,则您将报告最大值为0;否则为0。 if all the numbers are positive, you'll report that the minimum is 0. Fixing that is a tad fiddly, but you could use if (i == 0 || num < min) min = num; 如果所有数字都是正数,则将报告最小值为0。固定该操作有点麻烦,但可以使用if (i == 0 || num < min) min = num; etc. 等等


Linking Problem 链接问题

Your linking problem (undefined reference to sqrt() ) indicates that you are running on a system where you need to link the maths library; 您的链接问题(对sqrt()未定义引用)表明您正在一个需要链接数学库的系统上运行; that is usually -lm on the end of the linking command line. 在链接命令行的末尾通常是-lm


Synthesis 合成

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

int main(int argc, char*argv[])
{
    double average, num = 0, min = 0, max = 0, sum = 0, N, std_dev, sum_sqs = 0.0;

    if (argc <= 1)
    {
        fprintf(stderr, "Usage: %s file\n", argv[0]);
        return 1;
    }

    FILE *pFile = fopen(argv[1], "r");
    if (pFile == 0)
    {
        fprintf(stderr, "%s: failed to open file %s\n", argv[0], argv[1]);
        return 1;
    }
    if (fscanf(pFile, "%lf", &N) == 1)
    {
        for (int i = 0; i < N; i++)
        {
            if (fscanf(pFile, "%lF", &num) != 1)
            {
                fprintf(stderr, "%s: failed to read number\n", argv[0]);
                return 1;
            }

            if (num < min || i == 0)
                min = num;
            if (num > max || i == 0)
                max = num;
            sum += num;
            sum_sqs += (num*num);
        }
    }

    fclose(pFile);
    average = sum/N;
    std_dev = sqrt((sum_sqs/N)-(average*average));

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

Results 结果

Given data file data : 给定数据文件data

5    
4.34 23.4 18.92 -78.3 17.9

The result of running the program is: 运行该程序的结果是:

Smallest:  -78.30
Largest:   23.40
Average:   -2.75
Standard deviation:  38.309

Those values mostly look plausible; 这些价值似乎很合理。 my calculation of the standard deviation came to 42.83 (using a different tool altogether). 我的标准差计算结果为42.83(完全使用其他工具)。 The difference is between the sample standard deviation and the population standard deviation (a factor of √1.25) — so your value is OK as you calculated it. 差异是样本标准偏差和总体标准偏差(√1.25的因数)之间的差异,因此您计算得出的值就可以了。

# Count    = 5
# Sum(x1)  = -1.374000e+01
# Sum(x2)  =  7.375662e+03
# Mean     = -2.748000e+00
# Std Dev  =  4.283078e+01
# Variance =  1.834476e+03
# Min      = -7.830000e+01
# Max      =  2.340000e+01

So, the code works for me. 因此,代码对我有用。 What result are you getting? 你得到什么结果?

If you want the sqrt function, you need to add 如果要使用sqrt函数,则需要添加

#include <math.h>

to the top of your C file. 到C文件的顶部。

  • if you want to read a float with scanf , you should be using the %f format specifier, not %d (which will read an integer). 如果要使用scanf读取float ,则应使用%f格式说明符,而不是%d (它将读取整数)。
  • In your fopen call, remove the quotes around argv[1] , otherwise it'll look for a file with that name. 在您的fopen调用中,删除argv[1]周围的引号,否则它将查找具有该名称的文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C在浮点数组中找到2个最大数字和2个最小数字 - C find the 2 largest numbers and 2 smallest numbers in float array 交换C中最大和最小的数字 - Swapping largest and smallest numbers in C 使用数组编写C程序,以从100个随机数的列表中找到最大和最小的数 - Write a C program using array to find largest and smallest number from a list of 100 Random numbers 将文件中的结构变量(3 个整数)从最小到最大排序 C - Sorting structure variables(3 ints) in file from smallest to largest C 如何在C中找到最大和最小的数字 - How to find largest and smallest number in c c - 如何在数组中找到最大和最小的数字 - How to find the largest and smallest number in an array in c 在C中,我遇到了从文件中从最大到最小排序元素的算法的问题 - In C, I am having trouble with the algorithm of sorting elements from a file from largest to smallest 在 C 编程中找到五个数字中最大和第二大的数字 - find the largest and the second largest numbers out of five numbers in C programming 从文本文件中扫描数字并找到总和,最大数字和乘积 - Scanning in numbers from a text file and finding the sum,largest number, and product 查找三个输入数字中最大和最小的程序,并显示识别出的最大/最小数字是偶数还是奇数 - program to find the largest and smallest among three entered numbers and also display whether the identified largest/smallest number is even or odd
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM