【发布时间】: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 行(使用“编辑”链接并将其添加到问题中)
-
请添加您遇到的问题的实际错误