C 程序,从一个文件中获取一对数字,计算 newton(n,k),并将答案写入另一个文件

标签 c factorial

我需要一个程序的帮助,该程序从 txt 文件中获取一对数字,计算牛顿系数 (n!/(n! . (n-k)!)),并写下答案(分数) 到另一个 txt 文件。现在我有这个:

#include <stdio.h>

void factorial() {
    long l1, l2;
    long score = 1;
    for (int i = 1; i < l2; i++) {
        score = (score * (l1 - i + 1) / i);
    }
}

void read() {
    long l1, l2;
    long score = 1;
    FILE *file = fopen("pairs.txt", "r");
    FILE *file2 = fopen("sum.txt", "r");
    while (fscanf(file, "%ld%ld", &l1, &l2) == 2) {
        factorial();
        fprintf(file2, "%ld", score);
    }
    printf("Score is: %ld", score);
    fclose(file);
    fclose(file2);
}

int main() {
    read();
    return 1;
}

问题是,当我启动程序时,它显示答案 Score is: 1,并且文件 sum.txt 中没有任何内容。

最佳答案

您的代码中存在多个问题:

  • 您必须将参数传递给 binomial 函数,使用 return 语句返回结果并将返回值存储在调用代码中。

  • 您计算牛顿二项式系数的函数不正确。

  • 您应该打开输出文件 sum.txt 以使用 "w" 模式字符串进行写入。

  • 您应该检查 fopen() 是否成功打开文件。正如发布的那样,您的代码可能无法打开不存在的输出文件 sum.txt,因为它试图打开它进行阅读。因此 file2NULL 并且使用空流指针调用 fprintf 具有未定义的行为。这可以解释您观察到的崩溃。

这是更正后的版本:

#include <errno.h>
#include <stdio.h>
#include <string.h>

long binomial(long n, long k) {
    long value = 1;
    if (k < n - k) {
        k = n - k;
    }
    for (long i = n; i > k; i--) {
        value *= i;
    }
    for (long i = k; i > 1; i++) {
        value /= i;
    }
    return value;
}

int read(void) {
    long n, k, score;
    FILE *file1, *file2;

    file = fopen("pairs.txt", "r");
    if (file == NULL) {
        fprintf(stderr, "error opening pairs.txt: %s\n", strerror(errno));
        return 1;
    }
    file2 = fopen("sum.txt", "w");
    if (file2 == NULL) {
        fprintf(stderr, "error opening sum.txt: %s\n", strerror(errno));
        fclose(file);
        return 1;
    }
    while (fscanf(file, "%ld%ld", &n, &k) == 2) {
        score = binomial(n, k);
        fprintf(file2, "%ld\n", score);
    }
    //printf("Score is: %ld\n", score);
    fclose(file);
    fclose(file2);
    return 0;
}

int main(void) {
    return read();
}

关于C 程序,从一个文件中获取一对数字,计算 newton(n,k),并将答案写入另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42047038/

相关文章:

java - BigDecimal toPlainString 生成字符串需要很长时间

java - 使用 BigInteger 类的递归查找阶乘

c - 有关命令终止这一事实的信息,C 中的 Shell

Python ctypes 无法获取从 .so 文件返回的长字符串值

javascript - 使用 .reduce() 对数字进行因式分解

c - 阶乘和无法正常工作

Python 错误识别 int 值

c - 如何将 3d 指针数组传递给 c 中的函数?

c - 运行进程的重载符号(LD_PRELOAD附件)

c - float 不准确