gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:49 24 4
gpt4 key购买 nike

我需要一个程序的帮助,该程序从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com