C:函数不会在循环中运行并从文件中读取

时间:2016-03-21 20:09:40

标签: c

我正在尝试制作一个程序,将一个数字转换为其素数因子分解。例如,2048 = 2 ^ 11程序将输出211(因为该值将用于不同的函数)。程序然后在文件中打印素数因子分解和数字。我遇到的问题是拥有两个函数digitCount和FdigitCount,在循环中运行并从文件中读取值,然后将素数因子分解中的数字位数与正常数字中的位数进行比较,然后,如果它更少,打印出数字。

int digitCount(int n){
    int digits = 0;
    while(n!=0) {
        n/=10;             //divides the number by 10 and adds one to the digits   until it is no longer divisible by 10.
        ++digits;
    }
    return digits;
}

int fdigitCount(int p){ //this function is used the count the digits of the prime factorization.
    int fdigits = 0;
    while(p!=0) {
        p/=10;             //divides the number by 10 and adds one to the fdigits until it is no longer divisible by 10.
        ++fdigits;
    }
    return fdigits;
}


int main(void) {
    FILE* primes = NULL; //file pointer to the file that will contain all the prime factors of a number
    int num;
    int count;
    int digits;
    int limit;
    int i;
    int j=2;
    int fdigits;
    int frugalNum;
    int normNum;

    primes = fopen("primes.txt", "w+");
    if (primes == NULL){
        printf("Could not open primes.txt");
    }

    printf("Enter a limit: ");
    scanf("%d", &limit);
    for (i=2; i <= limit; i++){
        num = i;
        j = i;
        count = 0;
        if (num%2 == 0){
            while (num%2 == 0)
            {
                num = num/2;
                count++;
            }
            if (count > 1){
                fprintf(primes, "2%d", count);
            }
            else {
                fprintf(primes, "2");
            }
        }
        else if(num%2 != 0) {
            for (int i = 3; i <= sqrt(num); i = i+2)
            {
                // While i divides n, print i and divide n
                count = 0;
                while (num%i == 0)
                {
                    num = num/i;
                    count++;
                }
                if (count > 1){
                    fprintf(primes, "%d%d", i, count);
                }
                else if (count==1){
                    fprintf(primes, "%d", i);
                }
            }

        }
        if (num > 2){
            fprintf (primes, "%d", num);
        }
        fprintf(primes, " %d", j);
        fprintf(primes, "\n");
    }
    while (!feof(primes)){
        fscanf(primes, "%d %d", &frugalNum, &normNum);
        if (fdigitCount(frugalNum) < digitCount(normNum)){
            printf("%d\n", normNum);
        }
    }
    fclose(primes);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

feof()返回true之前,您不应该通过循环来读取文件。在您通过EOF后返回true,因此您读取的最后一个值将是垃圾。将你的循环改为:

while (fscanf(primes, "%d %d", &frugalNum, &normNum) == 2) {
    /* Do stuff with frugalNum and normNum */
}

此外,我无法注意到digitCount()fdigitCount()做同样的事情。你为什么需要这两个?