判断下fp,wf是否打开成功。
【以下回答由 GPT 生成】
首先,我们注意到代码中的一些错误和不规范之处,我们会逐步进行修改和优化。
#include <stdio.h>
#include <math.h>
double fun(int m, int n) {
// ...
}
int main() {
printf("P=%f\n", fun(12, 8));
return 0;
}
void NONO(void) {
FILE *fp, *wf;
int i, m, n;
double s;
// ...
}
-lm
选项来链接math库。修改编译命令如下:gcc -o filename filename.c -lm
这里的filename
是你的源代码文件名。
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;
}
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;
}
请注意,这只是一种解决方案,其他的方法也是可以的。如果还有其他问题,请随时告诉我。