所以我有这个文件myfile。txt其中包含以下数字:1 2 3 4 5 6 7 8 9 0 2 3 4 5 6 6 5 4 3 2 1
。我试着写一个程序来计算一个数字从0
到9
的重复次数,所以它会像Number %d repeats %d times
那样打印出来。现在我被困在打印文件的n个元素上了,举个例子,如果我想计算前15个数字重复了多少次,首先我要打印出这15个数字,然后是每个数字重复的次数。但是当我试图打印出这15个数字时,它打印给我的是:7914880640-10419997104210821064219560-1975428800327666414848
.
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main() {
FILE *fp;
fp = fopen("myFile.txt", "r");
char c;
int n, i, count = 0;
for (c = getc(fp); c != EOF; c = getc(fp)) {
if (!(c == ' '|| c == 'n'))
count = count + 1;
}
printf("The amount of numbers is:%dnTill which element of the list would you like to count the amount of the each element: n", count);
scanf("%d", &n);
int a[n];
if (n <= count) {
for (i = 0; i < n; i++) {
fscanf(fp, "%d", &a[i]);
}
for (i = 0; i < n; i++) {
printf("%d", a[i]);
}
} else {
printf("Error");
}
fclose(fp);
return 0;
}
这就是最终的解决方案。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int count_occur(int a[], char exist[], int num_elements, int value)
{
int i, count = 0;
for (i = 0; i<num_elements; i++)
{
if (a[i] == value)
{
if (exist[i] != 0)
return 0;
++count;
}
}
return(count);
}
int main()
{
int a[100],track[10];
FILE *fp;
fp = fopen("myFile.txt", "r");
char c,exist[20]= {0};
int n,i,num,count=0,k=0,eval;
for (c = getc(fp); c != EOF; c=getc(fp))
{
if (!(c==' '|| c=='n'))
count=count+1;
}
rewind(fp);
printf("The amount of numbers is:%dnTill which element of the list would you like to count the amount of the each element: n", count);
scanf("%d", &n);
if (n<=count)
{
while(fscanf(fp, "%d", &num) == 1)
{
a[k] = num;
k++;
}
for (i=0; i<n; i++)
{
printf("%d ", a[i]);
}
}
else
{
printf("Error");
}
fclose(fp);
if (n<=count)
{
for (i = 0; i<n; i++)
{
eval = count_occur(a, exist, n, a[i]);
if (eval)
{
exist[i]=1;
printf("nNumber %d was found %d timesn", a[i], eval);
}
}
}
return 0;
}