首页 > 解决方案 > 计算文件中的重复数字

问题描述

所以我有这个文件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:%d\nTill 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;
}

标签: arrayscfile

解决方案


这就是最终的解决方案。

#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:%d\nTill 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 times\n", a[i], eval);
            }
        }
    }

    return 0;
}

推荐阅读