簡體   English   中英

計算文件中的重復數字

[英]Count repeated numbers in a file

所以我有這個文件myFile.txt ,其中包含以下數字: 1 2 3 4 5 6 7 8 9 0 2 3 4 5 6 6 5 4 3 2 1 我正在嘗試編寫一個程序來計算從09的數字重復了多少次,所以它會像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;
}

這就是最終的解決方案。

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM