C 从文件中读取数字并将它们放入范围箱并打印到文件

C Reading numbers from file and placing them in range bins and printing to file

我对这个程序有疑问。

我想做的是从文件 input.txt 中读取行,其中第一行是文件中整数的数量。 input.txt 被格式化为

5 //整数个数
2
40
49
90
70

然后,我想打印到文件 output.txt 以便 output.txt 基本上是。

范围 0-9 1
范围 10-19 0
范围 20-29 0
范围 30-39 0
范围 40-49 2
范围 50-59 0
范围 60-69 0
范围 70-79 1
范围 80-89 0
范围 90-99 1

范围最多只能达到99。因此只有10个范围。所以在 input.txt.

中的初始行之后永远不会有超过 99 的数字

我遇到的问题是,只要猜测次数为 10,程序就可以正常工作。我知道这与我如何设置范围数字增加有关,因为它与循环有关。我不知道如何正确地做到这一点。

有什么建议吗?提前谢谢!

到目前为止我得到了什么:

/*

Print a numbers in range to file output.txt from the list of numbers in file input.txt

*/

#include <stdio.h>

int main(void)
{

FILE *input;
FILE *output;

int num_guesses, nums, bin_count=0, guesses_in_bin;
int i, j, k, firstline;
int Bin_Start = 0;
int bin[10];


input= fopen("input.txt", "r");
output= fopen("output.txt", "w");

fprintf(output, "Values        Amounts\n");

fscanf(input, "%d", &num_guesses); //scans first line of input.txt for the number of guesses

for (j=0; j< (num_guesses); j++) //for number of guesses run inside loop

{

    for (i=0; i< (num_guesses); i++)
    {
        fscanf(input, "%d", &nums);
        //printf("            %d\n", nums);
        if (nums >= Bin_Start && nums <= Bin_Start+9) //checks if number belongs in bin.
            bin_count = bin_count+1;






    }
    //rewind
    rewind(input);
    fscanf(input, "%d", &firstline); // used to ignore first line of file


    //reset bin count
    numbers_in_bin = bin_count;
    bin_count = 0;


    fprintf(output, "%2d - %2d      %d", Bin_Start, Bin_Start+9, numbers_in_bin);

    fprintf(output, "\n");

    //Update to next bin

    Bin_Start = Bin_Start+10;




}




fclose(input);
fclose(output);



return 0;
}

甚至不寻找或多或少的细微错误,就到此为止,这个解决方案在其概念上已经是错误的。解决这个问题的唯一明智的方法是预先为 所有十个可能的 bins 创建计数器,例如:

int bin[10] = { 0 };

然后扫描文件一次,然后做一些像

一样简单的事情
bin[input/10]++;

对于输出,循环你的垃圾箱,例如:

for (int i = 0; i < 10; ++i)
{
    printf("%d-%d:\t%d\n", 10*i, 10*i+9, bin[i]);
}