【问题标题】:C Programming - Generating Random Numbers into a new text File and retrieving them to count the occurrences (then do statistics on the side)C 编程 - 将随机数生成到一个新的文本文件中并检索它们以计算出现次数(然后在旁边进行统计)
【发布时间】:2025-11-23 13:55:02
【问题描述】:

我的目标是将随机数生成到一个新的 txt 文件中,我可以在其中检索随机生成的值并计算这些值的出现次数(例如,数字 1 出现了“x”次)。我的预期输出应显示与给定示例类似的输出,并且所有出现的次数加起来应为 600。我的 newfile() 函数的最后一个括号有一个下划线。提前致谢。

txt输出文件的前10行...

2

5

4

2

6

2

5

1

4

2

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int newfile(FILE *fp)
{
  char fname[20];
  printf("\nEnter the name of the file...  ");
  scanf("%19s",fname);//File name cannot have spaces
  strcat(fname, ".txt");
  fp=fopen(fname, "w");
  int i, N = 600, newfile[N];
  for(i=0;i<N;i++)
  {
     newfile[i]= ((rand() % 6)+1);
     fprintf(fp,"%d\n",newfile[i]);
  }
}

int main() 
{
  int i = 0;
  FILE *fp;
  do
  {
    newfile(fp);
    i++;
  }
  while (i<1);
    FILE* fpointer;
    char filename[20];
    int value = 0, result = 0, num[600] = { 0 };
    float sum, mean;

    printf("\nEnter the name of the file...  ");
    scanf("%19s",filename);
    fpointer = fopen(filename, "r");

    if (fpointer == NULL) {
        printf("ERROR: CANNOT OPEN FILE!\n");
        return -1;
    }

    result = fscanf(fpointer, "%d", &value);
    while (result == 1)
    {
        {
            num[value] = num[value] + 1;  // num[value]++
        }
        result = fscanf(fpointer, "%d", &value);
    }

    for (int i = 0; i <= 6; i++) {
        if (num[i] > 0) {
            printf("Number %i has appeared %d times\n", i, num[i]);
        }
    }
    
    sum = (1*(num[1])+2*(num[2])+3*(num[3])+4*(num[4])+5*(num[5])+6*(num[6]));

    mean = sum / 600;
    printf("\nThe mean is %f",mean);


    fclose(fpointer);
    return 0;
}

【问题讨论】:

  • 这里没有问题!!!
  • @goodvibration 抱歉。我只是想知道为什么我的代码没有按预期运行。
  • @Tee 以哪种方式“没有按预期运行”?
  • @Tee 发布 txt 文件的前 10 行(使用“编辑”链接并将其添加到问题中)
  • 请添加您遇到的问题的实际错误

标签: arrays c printf


【解决方案1】:

您的代码中的主要问题是您忘记关闭 newfile 函数中的文件。

所以只需在函数末尾添加fclose(fp);

小问题:

您不需要将fp 传递给函数newfile。只需使用局部变量即可。

newfile[N] 根本不需要。只需这样做:fprintf(fp,"%d\n", (rand() % 6)+1);

num[600] = { 0 }; 太大了,因为您只使用索引 0 .. 6

在执行num[value] = ... 之前,您应该检查value 是否在预期范围内,即避免写入越界。

【讨论】:

    最近更新 更多