让设计fun函数fun函数的功能是计算m!/(n!*(m-n)!),运行时变成了这样

img


让设计fun函数fun函数的功能是计算m!/(n!*(m-n)!),运行时变成了这样

判断下fp,wf是否打开成功。

【以下回答由 GPT 生成】

首先,我们注意到代码中的一些错误和不规范之处,我们会逐步进行修改和优化。

  1. 在开始之前,我们需要添加合适的头文件声明来使用一些库函数和类型声明:
#include <stdio.h>
#include <math.h>
  1. 修改函数fun()的返回类型为double,以便能够处理更大的计算结果:
double fun(int m, int n) {
    // ...
}
  1. 需要修改main()函数的声明方式为int main(),并在main()函数中删除对NONO()函数的调用:
int main() {
    printf("P=%f\n", fun(12, 8));
    return 0;
}
  1. 修改NONO()函数的声明为void NONO(void),并在函数内部添加合适的变量类型声明:
void NONO(void) {
    FILE *fp, *wf;
    int i, m, n;
    double s;
    // ...
}
  1. 如果希望在代码中使用math.h库中的阶乘函数,需要使用-lm选项来链接math库。修改编译命令如下:
gcc -o filename filename.c -lm

这里的filename是你的源代码文件名。

  1. 针对fun()函数中计算阶乘的部分,我们可以使用math.h库中的tgamma()函数来计算浮点数的阶乘。修改fun()函数如下:
double fun(int m, int n) {
    double a=1, b=1, c=1, p;

    for(int i=1; i<=m; i++) {
        a *= i;
    }
    for(int i=1; i<=n; i++) {
        b *= i;
    }
    for(int i=1; i<=m-n; i++) {
        c *= i;
    }

    p = a / (b * c);
    return p;
}
  1. 修改NONO()函数中的文件操作部分,包括打开文件、读取数据、计算结果和写入文件的过程:
void NONO(void) {
    FILE *fp, *wf;
    int m, n;
    double s;

    fp = fopen("in.dat", "r");
    if(fp == NULL){
        printf("Failed to open file.\n");
        return;
    }
    wf = fopen("out.dat", "w");
    if(wf == NULL){
        printf("Failed to create file.\n");
        fclose(fp);
        return;
    }

    for(int i=0; i<10; i++) {
        if(fscanf(fp, "%d %d", &m, &n) != 2) {
            printf("Failed to read data from file.\n");
            fclose(fp);
            fclose(wf);
            return;
        }

        s = fun(m, n);
        fprintf(wf, "%f\n", s);
    }

    fclose(fp);
    fclose(wf);
}

综上所述,修改后的代码如下所示:

#include <stdio.h>
#include <math.h>

double fun(int m, int n) {
    double a=1, b=1, c=1, p;

    for(int i=1; i<=m; i++) {
        a *= i;
    }
    for(int i=1; i<=n; i++) {
        b *= i;
    }
    for(int i=1; i<=m-n; i++) {
        c *= i;
    }

    p = a / (b * c);
    return p;
}

void NONO(void) {
    FILE *fp, *wf;
    int m, n;
    double s;

    fp = fopen("in.dat", "r");
    if(fp == NULL){
        printf("Failed to open file.\n");
        return;
    }
    wf = fopen("out.dat", "w");
    if(wf == NULL){
        printf("Failed to create file.\n");
        fclose(fp);
        return;
    }

    for(int i=0; i<10; i++) {
        if(fscanf(fp, "%d %d", &m, &n) != 2) {
            printf("Failed to read data from file.\n");
            fclose(fp);
            fclose(wf);
            return;
        }

        s = fun(m, n);
        fprintf(wf, "%f\n", s);
    }

    fclose(fp);
    fclose(wf);
}

int main() {
    printf("P=%f\n", fun(12, 8));
    NONO();
    return 0;
}

请注意,这只是一种解决方案,其他的方法也是可以的。如果还有其他问题,请随时告诉我。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^